[英]How to remove all characters after a certain character using Python 3
我需要知道如何使用 Python 3 在特定字符之后删除字符串中的所有字符。
例如对于字符串abcd (Read the tnc below!)
我只需要abcd
。 我想删除()
中的所有内容。
我现在可以使用这个 Python 代码:
mystr = "abcd (Read the tnc below!)"
char = ""
for c in mystr:
if c != "(":
char += c
else:
break
但在我看来,完成这样一个简单任务的代码又长又差。 我也尝试在网上搜索,但没有找到任何帮助。 Python 3 是否有一些很棒的正则表达式?
谢谢!
您可以使用re.sub
>>> mystr = "abcd (Read the tnc below!)"
>>>
>>> import re
>>> re.sub(r'\(.*', '', mystr)
'abcd '
删除括号之间的所有内容
>>> mystr = "abcd (Read the tnc below!)"
>>> re.sub(r'\(.*?\)', '', mystr)
'abcd '
我会做这样的事情:
mystr.split("(")[0]
我也会使用上面的split
解决方案,但是如果您正在寻找正则表达式,它就像^(.*?)\\(
- 这将匹配直到第一个开放括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.