如何替换字符串中的分隔逗号?

2024-09-28 13:18:11 发布

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

我有下面的字符串,我想把它解析成单词。这是一个连续的句子

text = "If it is hot , don’t touch"

到目前为止,我所尝试的:

import string

text = "If it is hot , don’t touch"

words = [word.replace(',', '') for word in text.split()]
print(words)

然而,我得到了以下结果:

['If', 'it', 'is', 'hot', '', 'don’t', 'touch']

因此,我想要的是:

['If', 'it', 'is', 'hot', 'don’t', 'touch']

2条回答

您可以使用筛选函数,而不是将“,”替换为“”
可以使用只返回不等于“,”的单词的函数 像这样:

words = [word for word in text.split() if word!=',']
text = "If it is hot , don’t touch"
newtext = text.replace(",", "")
words = newtext.split()
print(words)

相关问题 更多 >

    热门问题