在python中用多个匹配项分割字符串
我有一个字符串,必须对“words”中出现的单词进行拆分在python中用多个匹配项分割字符串,python,python-3.x,string,Python,Python 3.x,String,我有一个字符串,必须对“words”中出现的单词进行拆分 words=['word1','word2','word3'] text=“long statement word1 statement 1 word2 statement 2 word3 statement 3”#单行字符串 我使用的代码,有没有简单的方法 for l in words: if l == "word1": t1 = text.split(l) if l == &q
words=['word1','word2','word3']
text=“long statement word1 statement 1 word2 statement 2 word3 statement 3”#单行字符串
我使用的代码,有没有简单的方法
for l in words:
if l == "word1": t1 = text.split(l)
if l == "word2": t2 = str(t1[1]).split(l)
if l == "word3": t3 = str(t2[1]).split(l)
print(t1[0])
print(t2[0])
print(t3[0])
输出如下所示:
statement
statement1
statement2
statement3
如何使用:
输出:
['long statement', 'statement1', 'statement2', 'statement3']
你可以用Regex来解决你的问题
import re
words = ['word1', 'word2', 'word3']
text = " long statement word1 statement1 word2 statement2 word3 statement3 "
print(*re.split('|'.join(words),text), sep="\n")
您所需的输出与
text
以“long”开头的事实不匹配。您可以使用join-re.split(“|”).join(words),text)
@Anurag singh,对于此代码,我们需要进行打印(*re.split(strs,text),sep=“”)
否则代码会在新行中打印字符串中的每个字母。我是有意这样做的。正如最初发布的问题在新行上打印了拆分
import re
words = ['word1', 'word2', 'word3']
text = " long statement word1 statement1 word2 statement2 word3 statement3 "
print(*re.split('|'.join(words),text), sep="\n")