用小写+附加字符替换大写字符

2024-05-14 00:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到字符串中的所有大写字母,并将其替换为小写加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线。

请提出更好的解决方案。谢谢。


Tags: theto函数字符串namere标准caps
2条回答

试试这个。

string1 = "OneWorldIsNotEnoughToLive"
list1 = list(string1)
new_list = []
for i in list1:
    if i.isupper():
        i = "_"+i.lower()
    new_list.append(i)
print ''.join(new_list)

Output: _one_world_is_not_enough_to_live

为什么不使用一个简单的regex:

import re
re.sub('([A-Z]{1})', r'_\1','OneWorldIsNotEnoughToLive').lower()

# result '_one_world_is_not_enough_to_live'

相关问题 更多 >