如果我有一个字符串并想要返回一个包含空格的单词怎么办呢?
例如,我有:
line = 'This is a group of words that include #this and @that but not ME ME'
response = [ word for word in line.split() if word.startswith("#") or word.startswith('@') or word.startswith('ME ')]
print response ['#this', '@that', 'ME']
所以ME ME因空白而无法打印。
由于
答案 0 :(得分:1)
来自python文档:
string.split(s [,sep [,maxsplit]]):返回字符串s的单词列表。如果是可选的第二个 参数sep不存在或None,单词由任意分隔 空格字符串(空格,制表符,换行符,返回, 换页)。
因此,您的错误首先出现在拆分请求上。
print line.split() ['This','is','a','group','of','words','that','include','#this','and','@that','but' ,'不','我','我']
我建议使用re来分割字符串。使用 re.split(pattern,string,maxsplit = 0,flags = 0)
答案 1 :(得分:1)
你可以保持简单:
line = 'This is a group of words that include #this and @that but not ME ME'
words = line.split()
result = []
pos = 0
try:
while True:
if words[pos].startswith(('#', '@')):
result.append(words[pos])
pos += 1
elif words[pos] == 'ME':
result.append('ME ' + words[pos + 1])
pos += 2
else:
pos += 1
except IndexError:
pass
print result
只有在实践证明速度过慢时才考虑速度。