python去掉字符串中的标点符号
程序员文章站
2022-05-29 12:25:21
...
方法1:使用列表添加每个字符,最后将列表拼接成字符串
import string
def removePunctuation(text):
temp = []
for c in text:
if c not in string.punctuation:
temp.append(c)
newText = ''.join(temp)
print(newText)
text = "A man, a plan, a canal: Panama"
removePunctuation(text)
结果为:A man a plan a canal Panama
import string
def removePunctuation(text):
ls = []
for item in text:
if item.isdigit() or item.isalpha():
ls.append(item)
print("".join(ls))
text = "A man, a plan, a canal: Panama"
removePunctuation(text)
结果为:AmanaplanacanalPanama
方法2:join传递参时计算符合条件的字符
import string
def removePunctuation(text):
b = ''.join(c for c in text if c not in string.punctuation)
print(b)
text = "A man, a plan, a canal: Panama"
removePunctuation(text)
结果为:A man a plan a canal Panama