首页 > 解决方案 > 有什么方法可以忽略 Python 中的标点符号吗?

问题描述

请帮我解决以下问题:

有一个字符串:

Courses :- Thank You, Help me with this question, Have a good day

我想忽略“谢谢”和“课程”之间的任何标点符号。我现在正在做的是:

        if "Courses" in c:
        print(c)
        idx = c.index('-')
        while not c[idx].isalpha():
            idx += 1
        old_courses = c[idx:]
        print(old_courses)      

我可以得到:谢谢,帮我解决这个问题,祝你有美好的一天

但是“谢谢”和“课程”之间会有任何其他标点符号。我该怎么做才能得到与上面相同的东西?也许可以使用字符串模块。

谢谢你!!!

标签: pythonpython-3.xstring

解决方案


我会这样做

>>> s = "Courses :- Thank you, Help me with this question"
>>> punctuations = ['.',',',':','-']
>>> newstr = [x for x in s if not x in punctuations]
>>> newstr = ''.join(newstr)
>>> newstr
'Courses  Thank you Help me with this question'

您可能希望字符串中包含空格和数字。这就是我没有使用 isalpha 方法的原因。最好列出您想要删除的字符(或保留,更容易)。

希望我理解你的需要


推荐阅读