python去掉字符串中的标点符号

方法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


拓展:

Python之字符串转列表(split),列表转字符串(join)

发布了378 篇原创文章 · 获赞 43 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/105088692