python - 有什么方法可以忽略 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)
我可以得到:谢谢,帮我解决这个问题,祝你有美好的一天
但是“谢谢”和“课程”之间会有任何其他标点符号。我该怎么做才能得到与上面相同的东西?也许可以使用字符串模块。
谢谢你!!!
解决方案
我会这样做
>>> 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 方法的原因。最好列出您想要删除的字符(或保留,更容易)。
希望我理解你的需要
推荐阅读
- excel - 如何重命名与文件名不同的工作表名称
- python - 初始化 __init__ 参数列表中的对象以返回相同实例的默认值
- java - 是否可以使用 Kotlin/Java(包括(或不包括)端口)创建一个正则表达式来删除整个域(没有子域)?
- javascript - 将表单内外的数据保存到数据库中
- curl - Curl/LibCurl 的默认 DNS 解析行为、超时和重试间隔以及重试
- typescript - 产生的 put 动作未调度存储在回调中
- postgresql - 在标准 Helm 图表中将初始化容器添加到 pod
- java - 实现 Spring Security 后,Spring Boot ResponseBody 未序列化为 JSON
- javascript - 功能未定义,但已定义。反应和 Javascript
- html - 如何在 Bootstrap 中显示单词直到某个字数限制?