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
  • 7,071
  • 16
  • 58
  • 85
justachap
  • 313
  • 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
  • 58,805
  • 11
  • 114
  • 143
  • You could improve on the regular expression by making it either non-greedy (`.*?`) or by matching everything *except* a closing bracket (`[^\]]*`) instead of all characters. – Martijn Pieters Sep 14 '13 at 09:01
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
  • 85,663
  • 26
  • 103
  • 145