【问题标题】:Python : Ensure string is exactly in A.B.C format .. ( two dots separating 3 strings )Python:确保字符串完全是 A.B.C 格式..(两个点分隔 3 个字符串)
【发布时间】:2014-11-08 14:08:16
【问题描述】:

这段代码的问题是..

 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

但也许这是另一个问题。

【问题讨论】:

  • 这听起来像是... REGEX MAN 的工作!哒哒哒,哒哒哒哒 :-)
  • 你能说清楚你想要什么吗?请

标签: python python-2.7 python-2.6


【解决方案1】:
a = '1111.222.333'
b = a.split('.')
if len(b) != 3:
    print('Houston we have a problem.')
else:
    try:
        int(b[0]), int(b[1])
    except ValueError:
        print('First two really should be digits!')
    first = b[0]
    second = b[1]
    third = b[2]

请注意,这会捕捉到点太少和太多的情况。

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 他提到的拆分测试可能是:3 == len([p for p in a.split('.') if p != '']) OR 3 == len(filter(lambda x: x != '', a.split('.')))
    【解决方案3】:

    您可以将str.splittry/except 块一起使用,例如:

    s = '1111.222.333'
    try:
        first, second, third = s.split('.', 2)
    except ValueError:
        # do something suitable
    

    这里我们只在. 上拆分了两次,如果没有足够的参数来进行解包,那么会抛出ValueError 异常,然后你可以适当地处理它,否则你有firstsecondthird 已分配并准备就绪。

    如果不希望有超过三个,则取出str.split() 的第二个参数。然后except 块仍将运行,您可以随意处理它。

    【讨论】:

      猜你喜欢
      • 2018-01-06
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多