Extracting text in the middle of a string - python

3k views Asked by At

i was wondering if anyone has a simpler solution to extract a few letters in the middle of a string. i want to retrive the 3 letters (in this case, GMB) and all the entries follow the same patter. i'struggling o get a simpler way of doing this. here is an example of what i've been using.

entry = "entries-alphabetical.jsp?raceid13=GMB$20140313A"
symbol = entry.strip('entries-alphabetical.jsp?raceid13=')
symbol = symbol[0:3]
print symbol

thanks

2

There are 2 answers

0
Ashwini Chaudhary On BEST ANSWER

First of all the argument passed to str.strip is not prefix or suffix, it is just a combination of characters that you want to be stripped off from the string.

Since the string looks like an url, you can use urlparse.parse_qsl:

>>> import urlparse
>>> urlparse.parse_qsl(entry)
[('entries-alphabetical.jsp?raceid13', 'GMB$20140313A')]
>>> urlparse.parse_qsl(entry)[0][1][:3]
'GMB'
0
capturesteve On

This is what regular expressions are for. http://docs.python.org/2/library/re.html

import re
val = re.search(r'(GMB.*)', entry)
print val.group(1)