0

I am trying to find out if a string contains [city.----] and where the ---- is, any city could be in there. I just want to make sure it's formatted correctly. I've been searching for how I can ask Python to ignore that ---- but with no luck. Here is an example on how I would like to use this in the code:

if "[city.----]" in mystring:
    print 'success'
4

2 回答 2

5

您可以使用str.startswith()str.endswith()

if mystring.startswith('[city.') and mystring.endswith(']'):
    print 'success'

或者,您可以使用python 的切片表示法

if mystring[:6] == '[city.' and mystring[-1:] == ']':
    print 'success'

最后,您可以使用正则表达式

import re
if re.search(r'^\[city\..*?\]$', mystring) is not None:
    print 'success'
于 2013-09-14T08:17:07.827 回答
0

尝试使用re模块(这是关于正则表达式的HOWTO )。

>>> import re

>>> x = "asalkjakj [city.Absul Hasa Hii1] asjad a" # good string
>>> y = "asalkjakj [city.Absul Hasa Hii1 asjad a" # wrong string
>>> print re.match ( r'.*\[city\..*\].*', x )
<_sre.SRE_Match object at 0x1064ad578>
>>> print re.match ( r'.*\[city\..*\].*', y )
None
于 2013-09-14T08:19:45.107 回答