Python:抓住字符串中特定字符后的每个单词

2024-09-27 07:22:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想抓住每个前面有+的单词

如果我输入字符串:

 word anotherword +aspecialword lameword +heythisone +test hello

我要它回来:

 aspecialword heythisone test

Tags: 字符串testhello单词wordanotherwordaspecialwordlameword
3条回答

你可以用正则表达式。你知道吗

>>> import re
>>> re.findall(r'(?<=\+)\S+', "word anotherword +aspecialword lameword +heythisone +test hello")
['aspecialword', 'heythisone', 'test']

r'(?<=\+)\S+'匹配前面有加号的任何非空格字符序列。你知道吗

试着这样做:

>>> 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与list comp组合

>>> a = 'word anotherword +aspecialword lameword +heythisone +test hello'
>>> [i[1:] for i in a.split() if i[0] == '+']
['aspecialword', 'heythisone', 'test']

相关问题 更多 >

    热门问题