python:在列表中的元素中获取子字符串

时间:2010-08-02 19:11:56

标签: python

row=['alex','liza','hello **world**','blah']

我是否在row[2]中获取**个字符之间的所有内容?

4 个答案:

答案 0 :(得分:3)

可以手动执行此操作并搜索*,但也可以使用正则表达式。

print re.search(r'\*\*(.*)\*\*', 'hello **world**').group(1) # prints 'world'

你需要知道完全你正在寻找的正则表达式,所以想想**asd**dfe**和类似的边缘情况应该返回什么。

答案 1 :(得分:1)

import re
print re.findall(r"\*\*(.*)\*\*", row[2])

将为您提供row[2]**之间所有匹配项的列表。根据需要微调正则表达式

答案 2 :(得分:1)

假设您不知道哪个元素有星星,您可以使用它:

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)

答案 3 :(得分:0)

row [2] .strip('*')

刀可以使用电锯。

相关问题