我希望從客戶端字串中洗掉“#”。
假設字串是“#Freahlife 我剛吃了一個蘋果”
我想寫一個函式并只提取“我剛吃了一個蘋果”
我怎樣才能通過使用python來實作這一點?謝謝!
uj5u.com熱心網友回復:
您可以使用 python 的re模塊。
import re
re.sub(r"#\w \s?", "", "#Freahlife I just ate an apple")
Out[8]: 'I just ate an apple'
uj5u.com熱心網友回復:
如果#僅后跟Freahlife,您可以使用replace@anosha_rehan 提到的功能。但是如果后面的單詞是未知的,你可以使用split函式并將所有單詞放在一個串列中。然后,您可以回圈并檢查是否#在當前單詞中并且索引為 0(確保#在單詞的開頭找到)。然后,從串列中洗掉它并將串列轉換為字串。
uj5u.com熱心網友回復:
您可以使用該replace函式并strip洗掉任何空格:
'#Freahlife I just ate an apple'.replace('#Freahlife','').strip()
或通用:
' '.join('#Freahlife I just ate an apple'.split(' ')[1:])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451728.html
上一篇:在R中創建單詞變體
