是否可以用特殊格式比较字符串

时间:2018-07-20 05:35:09

标签: python python-3.x

截至目前,这将产生false。我只想知道是否可以设置一个变量来设置类似特殊格式的字符串

sting_prime = str, str

x = "jon, doe" 

print (x == sting_prime)

因此,在此示例中,我希望字符串格式为带有逗号的字符串,后跟一个空格和另一个字符串。由于x的格式相同,所以我希望它产生True。

1 个答案:

答案 0 :(得分:4)

您可以为此使用正则表达式。以下代码中的正则表达式非常基本,但是您可以根据需要进行更改。

import re


STRING_EXP = '[a-zA-Z]+' # basic expression to match ascii strings. write more complicated ones for your needs
INT_EXP = '[0-9]+'    # basic expression to match integer

schema = "{}, {}".format(STRING_EXP, STRING_EXP)
text = "jon, jdoe"
print(True if re.search(schema, text) else False) # prints True

text = "1, 2"
print(True if re.search(schema, text) else False) # prints False

# change schema
schema = "{}, {}".format(INT_EXP, INT_EXP)
print(True if re.search(schema, text) else False) # prints True
相关问题