Pages

Sunday, October 28, 2012

substring search in python

Let's say you want to extract "add" from "abc()", you have a couple of choices in Python.

string#find

string object has find() method to get the position that matches the substring.
str = "add()"
pos = str.find("(")
str[0:pos]

You can have one liner.
str[0:str.find("(")]

regular expression

Regular expression in python has two favors, one is compile()/match(), and the other one is search().
re.compile(r'([^\)]*)\(\)').match(str).group(1)
re.search(r'([^\)]*)\(\)', str).group(1)

Reference

No comments:

Post a Comment