如果它包含某個字符,我試圖從字串中取出一個單詞。
我想做這樣的事情:
string = 'My email is [email protected] and I use it a lot.'
if '@' in string:
return email
但是我怎樣才能讓 python 準確地知道關鍵字在哪里并回傳它的值。
在這種情況下,它會回傳[email protected]
uj5u.com熱心網友回復:
您也可以將正則運算式用于您的目的。在此正則運算式模式中,\S*表示“任何非空白字符”。您可以在此處測驗正則運算式。
import re
string = 'My email is [email protected] and I use it a lot.'
search_word = re.search(r'(\S*)@(\S*)', string)
if search_word:
print(search_word.group())
else:
print("Word was not found.")
uj5u.com熱心網友回復:
使用串列理解:
emails = [i for i in string.split() if '@' in i]
輸出:
['[email protected]']
uj5u.com熱心網友回復:
使用正則運算式提取您感興趣的模式,例如:
import re
email = re.search('\w @\w ([.]\w ) ', string).group(0)
uj5u.com熱心網友回復:
match=re.search(r'([^\s]*@[^\s]*)',string)
if match and match.group(0): print(match.group(0))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420066.html
標籤:
上一篇:雪花最近一個財政季度的最后一天
