擅长:python、mysql、java
<p>根据<a href="https://docs.python.org/3/library/stdtypes.html#str.replace" rel="nofollow noreferrer">official document</a>,<code>replace</code>函数的第一个参数是要替换的字符串。
因此,<code>some_str.replace('()','')</code>意味着替换字符串中未找到的所有<code>()</code>,因此replace函数返回相同的字符串</p>
<p>有三种方法可以解决这个问题</p>
<ol>
<li><p>使用多个替换函数</p>
<p>由于一次只能替换一种类型的子字符串,因此我们可以使用它两次来实现我们的目的</p>
<pre><code>your_str = your_str.replace('(','').replace(')','')
</code></pre>
</li>
<li><p>使用正则表达式库<code>re.sub()</code></p>
<p><code>re.sub()</code>(<a href="https://docs.python.org/3/library/re.html?highlight=re#re.sub" rel="nofollow noreferrer">doc</a>)函数更强大,可以在一次调用中指定要替换的不同子字符串</p>
<p><strong>对我来说,我更喜欢这个解决方案,因为它更灵活、更强大。</strong></p>
<pre><code>import re
your_str = re.sub(r'[\)\(]', '', your_str)
</code></pre>
</li>
<li><p>使用<code>str.strip()</code>(<a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow noreferrer">doc</a>)</p>
<p><code>str.strip()</code>函数只会删除字符串末尾的<strong>字符</strong>,您还可以指定要删除的<strong>多个字符</strong>。
因此,在这种情况下,它是有用的</p>
<pre><code>your_str = your_str.strip('()')
</code></pre>
</li>
</ol>