extracting a substring
Gary Herron
gherron at islandtraining.com
Tue Apr 18 20:42:13 EDT 2006
b83503104 at yahoo.com wrote:
>Hi,
>I have a bunch of strings like
>a53bc_531.txt
>a53bc_2285.txt
>...
>a53bc_359.txt
>
>and I want to extract the numbers 531, 2285, ...,359.
>
>One thing for sure is that these numbers are the ONLY part that is
>changing; all the other characters are always fixed.
>
>I know I should use regular expressions, but I'm not familar with
>python, so any quick help would help, such as which commands or idioms
>to use. Thanks a lot!
>
>
>
Try this:
>>> import re
>>> pattern = re.compile("a53bc_([0-9]*).txt")
>>>
>>> s = "a53bc_531.txt"
>>> match = pattern.match(s)
>>> if match:
... print int(match.group(1))
... else:
... print "No match"
...
531
>>>
Hope that helps,
Gary Herron
More information about the Python-list
mailing list