<p>我试图找到字符串中的所有大写字母,并将其替换为小写加<code>underscore</code>字符。AFAIK没有标准的字符串函数来实现这个(?)</p>
<p>例如,如果输入字符串是<code>'OneWorldIsNotEnoughToLive'</code>,那么输出字符串应该是<code>'_one_world_is_not_enough_to_live'</code></p>
<p>我可以用下面的代码来完成它:</p>
<pre><code># This finds all the uppercase occurrences and split into a list
import re
split_caps = re.findall('[A-Z][^A-Z]*', name)
fmt_name = ''
for w in split_caps:
fmt_name += '_' + w # combine the entries with underscore
fmt_name = fmt_name.lower() # Now change to lowercase
print (fmt_name)
</code></pre>
<p>我觉得这太过分了。首先是<code>re</code>,然后是列表迭代,最后转换为小写。也许有一个更简单的方法来实现这个,更多的Python和1-2线。</p>
<p>请提出更好的解决方案。谢谢。</p>
<p>为什么不使用一个简单的regex:</p>
<pre><code>import re
re.sub('([A-Z]{1})', r'_\1','OneWorldIsNotEnoughToLive').lower()
# result '_one_world_is_not_enough_to_live'
</code></pre>