擅长:python、mysql、java
<p>您可以使用<a href="https://docs.python.org/2/library/re.html#text-munging" rel="nofollow noreferrer">re.sub()</a>。如果<code>"Return"</code>子字符串出现在末尾,则会删除它,否则不会。你知道吗</p>
<p>让我们做一个函数<code>substring_remover()</code></p>
<pre><code>import re
def substring_remover(whole_string):
return re.sub(r'(.+)(Return)$',r'\1',whole_string)
print substring_remover('omarReturn') # Will remove "Return" as it is at the end
print substring_remover('omarNormal') # Will remove nothing as there is no "Return"
print substring_remover('omarReturnExtra') # Will remove nothing because "Return" exists but not at the end.
</code></pre>
<p>输出:</p>
<pre><code>omar
omarNormal
omarReturnExtra
</code></pre>
<p>所以,确切的代码是:</p>
<pre><code>with open('your_file','rw') as f:
print '\n'.join([substring_remover(line) for line in f.read().splitlines()])
f.seek(0)
f.write(value)
f.truncate()
</code></pre>