[英]Remove characters outside quotation mark python
如何刪除引號外的所有字符,例如這是我的字符串
message = 'something "like" this'
print( removeFromQuote(message) )
message2 = 'something "like this" thank you!'
print( removeFromQuote(message2) )
然后結果:
喜歡
像這樣
如何創建可以執行此操作的功能removeFromQuote。
或使用帶有正確正則表達式的re.sub
先感謝您!
嘗試使用findall
:
import re
message = 'something "like this" thank you'
print(re.findall('"(\D+)"',message)[0])
輸出:
like this
首先,將字符串拆分為引號。
message = 'something "like" this'
chunks = message.split('"')
列表中作為引號內的文本位的元素是奇數個。 所以就拿那些。
odd_chunks = chunks[1::2]
現在,將列表重新組合成一個字符串。
result = "".join(odd_chunks)
放在一起:
def removeFromQuote(text):
return "".join(text.split('"')[1::2])
您可以使用正則表達式:
import re
def removeFromQuote(message):
return re.findall(r'"(.+?)"', message)
結果如下:
>>> message = 'something "like this" or "like that"'
>>> removeFromQuote(message)
['like this', 'like that']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.