首页 > 解决方案 > 不能让它成为一个列表 - python

问题描述

我搜索并回答,但找不到答案。

我无法将该 str 添加到列表中,如何将其打印为列表?

请指教。

punctuation = ['.','(',')','?',':',':',',','.','!','/','"',"'",'@','#','$','%','^','&','*']
tokenize = str(input("Please enter a sentence " ))
tokenize = "".join(char for char in tokenize if char not in punctuation)
print ("Tokenized:",tokenize.lower())

标签: pythonstringpython-3.xlist

解决方案


您可以使用re.split交替模式:

import re
punctuation = ['.','(',')','?',':',':',',','.','!','/','"',"'",'@','#','$','%','^','&','*']
tokenize = str(input("Please enter a sentence: " ))
print(re.split('|'.join(map(re.escape, punctuation)), tokenize))

样本输入和输出:

Please enter a sentence: Hello,World!foo:bar
['Hello', 'World', 'foo', 'bar']

推荐阅读