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'
perror
  • 6,737
  • 16
  • 59
  • 77
justachap
  • 303
  • 1
  • 5
  • 12

2 Answers2

5

You can use str.startswith() and str.endswith():

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

Alternatively, you can use python's slice notation:

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

Lastly, you can use regular expressions:

import re
if re.search(r'^\[city\..*?\]$', mystring) is not None:
    print 'success'
Community
  • 1
  • 1
TerryA
  • 56,204
  • 11
  • 116
  • 135
0

Try something using re module (Here's the HOWTO about regular expressions).

>>> 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
kender
  • 82,935
  • 24
  • 100
  • 144