Python:抓取字符串中某个字符后的每个单词
Python: Grab each word after certain character in string
我想抓取前面有 + 的每个单词
如果我输入字符串:
word anotherword +aspecialword lameword +heythisone +test hello
我想要 return:
aspecialword heythisone test
这样试试:
>>> my_str = "word anotherword +aspecialword lameword +heythisone +test hello"
>>> " ".join(x[1:] for x in my_str.split() if x.startswith("+"))
'aspecialword heythisone test'
str.startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
有一个 split
与列表组合
>>> a = 'word anotherword +aspecialword lameword +heythisone +test hello'
>>> [i[1:] for i in a.split() if i[0] == '+']
['aspecialword', 'heythisone', 'test']
您可以使用正则表达式。
>>> import re
>>> re.findall(r'(?<=\+)\S+', "word anotherword +aspecialword lameword +heythisone +test hello")
['aspecialword', 'heythisone', 'test']
r'(?<=\+)\S+'
匹配前面有加号的任何非 space 字符序列。
我想抓取前面有 + 的每个单词
如果我输入字符串:
word anotherword +aspecialword lameword +heythisone +test hello
我想要 return:
aspecialword heythisone test
这样试试:
>>> my_str = "word anotherword +aspecialword lameword +heythisone +test hello"
>>> " ".join(x[1:] for x in my_str.split() if x.startswith("+"))
'aspecialword heythisone test'
str.startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
有一个 split
与列表组合
>>> a = 'word anotherword +aspecialword lameword +heythisone +test hello'
>>> [i[1:] for i in a.split() if i[0] == '+']
['aspecialword', 'heythisone', 'test']
您可以使用正则表达式。
>>> import re
>>> re.findall(r'(?<=\+)\S+', "word anotherword +aspecialword lameword +heythisone +test hello")
['aspecialword', 'heythisone', 'test']
r'(?<=\+)\S+'
匹配前面有加号的任何非 space 字符序列。