【发布时间】:2014-08-06 07:33:50
【问题描述】:
我正在尝试查找字符串中的所有大写字母并将其替换为小写加上underscore 字符。 AFAIK 没有标准的字符串函数来实现这个(?)
例如如果输入字符串是'OneWorldIsNotEnoughToLive',那么输出字符串应该是'_one_world_is_not_enough_to_live'
我可以使用以下代码来做到这一点:
# 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)
我认为这太过分了。首先re,然后是列表迭代,最后转换为小写。也许有更简单的方法来实现这一点,更多的pythonic和1-2行。
请提出更好的解决方案。谢谢。
【问题讨论】:
-
这不是代码编写服务。你为什么不看看the
strmethods。 “没有标准的字符串函数” - 你在期待什么,str.uppercase_to_lowercase_with_underscores? -
我知道 SO 不是代码编写服务。只是想看看有没有更好的解决方案,更多的pythonic和1-2行。
-
如果你想检查工作代码,试试codereview.stackexchange.com
-
@jonrsharpe 感谢您的链接。我不知道 codereview.stackexchange.com 我会看看。按照标准,我的意思是用某种模式替换字符串。
标签: python regex string str-replace