用小写+额外字符替换大写字符

时间:2014-08-06 07:33:50

标签: python regex string str-replace

我正在尝试查找字符串中的所有大写字母,并将其替换为小写加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行。

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

3 个答案:

答案 0 :(得分:6)

为什么不是一个简单的正则表达式:

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

# result '_one_world_is_not_enough_to_live'

答案 1 :(得分: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

答案 2 :(得分:2)

string = input()

for letter in string:
    if letter.isupper():
        string = string.replace(letter, "_" + letter.lower())
print(string)
相关问题