所以我在示例列表中有这个有问题的字符串:
pM = ['sam DM @carl hello friends do you know each other, @james?']
我需要一种方法在“@”符号之后打印两个名称到目前为止我只能想出如何打印一个IE:
def mentioned():
for s in pM:
if "@" in s:
userName = s.split()
single = (userName[3])
data.append(single)
else:
None
答案 0 :(得分:3)
使用正则表达式:
import re
pM = ["sam DM @carl hello friends do you know each other", "@james?"]
for i in pM:
print(re.findall("\@[a-z]+", i)[0])
<强>输出:强>
@carl
@james
答案 1 :(得分:1)
你也可以试试这个:
import re
pM = ['sam DM @carl hello friends do you know each other, @james?']
list1 = pM[0].split(' ')
x = [ele for ele in list1 if re.split('@', ele) and '@' in ele] # This will filter the strings with '@' in it
for name in x:
print(re.split('@', name)[1]) # This prints only the names 'carl', 'james'
输出:
['@carl', '@james?']
carl
james
如果您不想使用import re
,请使用以下代码:
for ele in pM[0].split():
if '@' in ele or '?' in ele:
print(ele.strip('@?'))
输出:
carl
james