I need to know how we can remove all the characters in a string after a certain characters using Python 3.
For example for the string abcd (Read the tnc below!)
I need only abcd
. I want to remove all what we have in the ()
.
I can use this Python code for now:
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?
Thanks!
You can use 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
解决方案,但是如果您正在寻找正则表达式,它就像^(.*?)\\(
- 这将匹配直到第一个开放括号
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.