python: getting substring within element in list
row=['alex','liza','hello **world**','blah']
开发者_如何学Go
i do i get everything in row[2]
that is between the **
characters?
You could do it by hand and search for the *
, but regex work too.
print re.search(r'\*\*(.*)\*\*', 'hello **world**').group(1) # prints 'world'
You need to know exactly what you're looking for with regex, so think about what **asd**dfe**
and similar edge cases should return.
import re
print re.findall(r"\*\*(.*)\*\*", row[2])
will give you a list of every match in row[2]
which is between **
. Fine tune the regex as necessary
Let's say that you don't know which element has the stars, you could use this:
row=['alex','liza','hello **world**','blah']
for staritem in (item for item in row if '**' in item):
print(staritem)
_,_, staritem = staritem.partition('**')
staritem,_,_ = staritem.partition('**')
print(staritem)
row[2].strip('*')
Don't use a chainsaw when a knife will do.
精彩评论