[英]How to remove all characters after a certain character using Python 3
I need to know how we can remove all the characters in a string after a certain characters using Python 3.我需要知道如何使用 Python 3 在特定字符之后删除字符串中的所有字符。
For example for the string abcd (Read the tnc below!)
I need only abcd
.例如对于字符串abcd (Read the tnc below!)
我只需要abcd
。 I want to remove all what we have in the ()
.我想删除()
中的所有内容。
I can use this Python code for now:我现在可以使用这个 Python 代码:
mystr = "abcd (Read the tnc below!)"
char = ""
for c in mystr:
if c != "(":
char += c
else:
break
But that seems to me to be the long and bad code for doing such a simple task.但在我看来,完成这样一个简单任务的代码又长又差。 I tried searching online too, but didn't find any help.我也尝试在网上搜索,但没有找到任何帮助。 Does Python 3 have some great regex for it? Python 3 是否有一些很棒的正则表达式?
Thanks!谢谢!
You can use re.sub
您可以使用re.sub
>>> mystr = "abcd (Read the tnc below!)"
>>>
>>> import re
>>> re.sub(r'\(.*', '', mystr)
'abcd '
To remove everything between parenthesis删除括号之间的所有内容
>>> mystr = "abcd (Read the tnc below!)"
>>> re.sub(r'\(.*?\)', '', mystr)
'abcd '
我会做这样的事情:
mystr.split("(")[0]
我也会使用上面的split
解决方案,但是如果您正在寻找正则表达式,它就像^(.*?)\\(
- 这将匹配直到第一个开放括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.