Python:确保字符串完全是A.B.C格式。。(两个点分隔3个字符串)
此代码的问题是Python:确保字符串完全是A.B.C格式。。(两个点分隔3个字符串),python,python-2.7,python-2.6,Python,Python 2.7,Python 2.6,此代码的问题是 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个字符串 更新: 第一个和第二个始终是数字,最后一个始终是“测试”文本 换句话
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+\.测试当前与以下匹配:
\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,那么如果需要,您可以不使用regex来执行测试。您可以按句点拆分字符串,检查结果列表的长度,然后独立地检查每个组件。如果长度不是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
一种解决方案可能是使用正则表达式:
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+\.测试当前与以下匹配:
\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,那么如果需要,您可以不使用regex来执行测试。您可以按句点拆分字符串,检查结果列表的长度,然后独立地检查每个组件。如果长度不是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
请注意,这会捕获太少和太多圆点的情况
请注意,这会捕获点太少或太多的情况。您可以将str.split与try/except块一起使用,例如:
s = '1111.222.333'
try:
first, second, third = s.split('.', 2)
except ValueError:
# do something suitable
在这里,我们只分了两次。如果没有足够的参数让解包工作,那么会抛出ValueError异常,然后您可以适当地处理它,否则您已经分配了第一、第二和第三个参数,并且可以开始了
如果不需要三个以上的参数,请将第二个参数去掉到str.split。然后,except块仍将运行,您可以根据需要处理它。您可以将str.split与try/except块一起使用,例如:
s = '1111.222.333'
try:
first, second, third = s.split('.', 2)
except ValueError:
# do something suitable
在这里,我们只分了两次。如果没有足够的参数让解包工作,那么会抛出ValueError异常,然后您可以适当地处理它,否则您已经分配了第一、第二和第三个参数,并且可以开始了
如果不需要三个以上的参数,请将第二个参数去掉到str.split。except块仍将运行,您可以根据需要处理它。这听起来像是。。。雷格斯曼!达达达,达达达达:你能说清楚你想要什么吗?这听起来像是。。。雷格斯曼!达达达,达达达达:你能说清楚你想要什么吗?他提到的分割测试可能是:3==len[p代表a.split中的p'.'如果p!=]或3==lenfilterlambda x:x!=,a、 他提到的分割测试可以是:3==len[p代表a.split中的p'.'如果p!=]或3==lenfilterlambda x:x!=,a、 拆分“.”