Cod*_*ogh 0 python regex string replace python-3.x
我需要知道如何使用 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
Run Code Online (Sandbox Code Playgroud)
但在我看来,对于完成如此简单的任务来说,这似乎是又长又糟糕的代码。我也尝试在网上搜索,但没有找到任何帮助。Python 3 有一些很棒的正则表达式吗?
谢谢!
您可以使用re.sub
>>> mystr = "abcd (Read the tnc below!)"
>>>
>>> import re
>>> re.sub(r'\(.*', '', mystr)
'abcd '
Run Code Online (Sandbox Code Playgroud)
删除括号之间的所有内容
>>> mystr = "abcd (Read the tnc below!)"
>>> re.sub(r'\(.*?\)', '', mystr)
'abcd '
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1467 次 |
| 最近记录: |