簡體   English   中英

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

[英]python: getting substring within element in list

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

我是否將row[2]中的所有內容都放在**字符之間?

可以手工完成並搜索* ,但是正則表達式也可以。

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

您需要確切地知道您要使用正則表達式查找的內容,因此請考慮應返回什么**asd**dfe**和類似的邊緣情況。

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

將為您提供row[2]中每個匹配項的列表,介於**之間。 根據需要微調正則表達式

假設您不知道哪個元素具有星號,則可以使用以下方法:

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)

行[2] .strip( '*')

有刀時不要用鏈鋸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM