Skip to main content
 首页 » 编程设计

Python : Ensure string is exactly in A. B.C 格式 ..(两个点分隔 3 个字符串)

2025年05月04日27kenshinobiy

这段代码的问题是..

 a = '1111.222.333' 
 
 b = a.split('.') 
 
 first = b[0] 
 second = b[1] 
 third = b[2] 

是..如果字符串缺少部分,例如..

   a = '222.333' 
 
the "second" can end up becoming "first" 

我想确保字符串是..

 111.222.333 

格式。换句话说有 2 个点分隔 3 个字符串

更新:

第一个和第二个总是数字,最后一个总是“测试”文本..

换句话说:111.222.test

但也许这是另一个问题。

请您参考如下方法:

一个解决方案可能是使用正则表达式:

import re 
 
a = '1111.222.333' 
 
def does_string_match(a): 
    return re.match('\d+\.\d+\.test', a) is not None 
 
print does_string_match(a)  # returns True 

模式 \d+\.\d+\.test 当前匹配:

\d+     1 or more numeric digits 
\.      A literal period 
\d+     1 or more numeric digits 
\.      A literal period 
test    The literal text 'test' 

如果字符串始终采用 num.num.test 格式,您可以根据需要在不使用正则表达式的情况下执行测试。您可以按句点拆分字符串,检查结果列表的长度,然后独立检查每个组件。如果长度不是 3,或者如果任何组件是您不接受的值,那么您就知道出了问题。

def does_string_match(a): 
    try: 
        # If you can't unpack a.split into 3 pieces, Python throws a ValueError 
        first, second, third = a.split('.')  
 
        # If you can't convert first or second to ints, Python throws a ValueError 
        int(first) 
        int(second) 
 
        if third != 'test': 
            return False 
    except ValueError: 
        return False 
 
    return True