如何确保字符串格式正确

时间:2014-05-27 23:59:43

标签: python string list

我需要确保输入的字符串格式正确。它必须采用以下格式: &#39; #### #### #### ####&#39;像信用卡号码。如何确保我的代码不会接受类似于&#39; 1234 5678 12345678&#39;但接受&#39; 1234 5678 1234 5678&#39;。我不知道该如何解决这个问题。我尝试过使用len函数,但无论格式如何,都可以接受len为19的任何东西。我的猜测是我需要把它分成4个字符串并确保它们都是4个字符长,但我不知道该怎么做,或者即使这是正确的方法。< / p>

3 个答案:

答案 0 :(得分:3)

s='1234 5678 1234 5678'

all([len(x) == 4 for x in s.split()])
True

s='1234 5678 12345678'
all([len(x) == 4 for x in s.split()])
False

要检查全部也是数字:

s='1234 5678 1234 t578'
   all([len(x) == 4 and x.isdigit() for x in s.split()])
   False

使用split,将字符串拆分为空格。

所以如果s = '1234 5678 1234 5678' 使用list comprehension [x for x in s.split()] x.split()创建列表['1234', '5678', '1234', '5578']

检查all([len(x) == 4 for x in s.split()])可确保所有元素长度为四个字符,x.isdigit()确保它们是数字。

您可以进行if len(s.split())==4之类的初步检查,因为列表中必须有四个元素才能匹配您所需的输入。因此,即使用户添加了"1234 5678 1234"之类的输入,您也会捕获该错误。

s='1234 5678 1234 5568'
if len(s.split())==4 and all([len(x) == 4 and x.isdigit() for x in s.split()]):
    print "all good"
all good

答案 1 :(得分:2)

使用正则表达式:

import re
p=re.compile('[0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4}')

p.match('1234 5678 1234 5678')

应返回匹配对象,而 p.match('ABCD EFGH IJKL MNOP')将返回None

答案 2 :(得分:1)

尝试使用re库(正则表达式)。有一个很好的首发in this book(以及其他许多好东西)。

import re

pattern = re.compile(r'''
    ^          # match the beginning of the string
    (\d{4})    # match a group of 4 numbers and remember that group
    \D*        # optional separator of any number of non-digit characters
    (\d{4})    # match second group of 4 numbers
    \D*
    (\d{4})    # third group
    \D*
    (\d{4})    # fourth group
    $          # end of string
    ''', re.VERBOSE)

pattern.search(input_string).groups()    # returns the saved groups of 4 digits each in a list
pattern.match(input_string) is not None  # returns true or false (match or no match)

请注意,此解决方案仅匹配四组,每组四个数字。这意味着像'1234 5678 1234 5678'这样的条目会被解析为('1234', '5678', '1234', '5678')之类的列表,因此'1234567812345678',甚至'1234 regex = cool 56781234 wewt regex 5678'等条目也会被解析。那里有一些灵活性。请注意,开头的^和结尾的$表示字符串的开头必须位于第一个数字组之前,而结尾必须位于最后一个数字组之后比赛。你可以通过省略它们来使它更灵活。

要完全匹配您想要的内容,请尝试使用pattern = re.compile(r'^(\d{4}) (\d{4}) (\d{4}) (\d{4})$')

如果您不关心在列表中返回数字,只要输入字符串是否与您的格式匹配,那么@caoy就是正确的,省略括号(它们将匹配存储为一组),并使用pattern.match(string)命令。

编辑:使用详细的正则表达式来包含分隔符。以前,如果数字组之间有空格或任何其他内容,则会失败。现在第一种模式非常普遍,最后一种模式非常具体。

编辑2:只是检查字符串是否与模式匹配。

相关问题