我试图找到字符串中的所有大写字母,并将其替换为小写加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
,然后是列表迭代,最后转换为小写。也许有一个更简单的方法来实现这个,更多的Python和1-2线。
请提出更好的解决方案。谢谢。
试试这个。
为什么不使用一个简单的regex:
相关问题 更多 >
编程相关推荐