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

3 投票
3 回答
16912 浏览
提问于 2025-04-18 16:12

我想在一个字符串中找到所有的大写字母,并把它们替换成小写字母加上一个下划线。据我所知,没有标准的字符串函数可以做到这一点(?)

比如,如果输入的字符串是'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行代码。

请给我一些更好的建议。谢谢。

3 个回答

2
string = input()

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

这段代码是用来做某些操作的,但具体的功能和用途需要根据上下文来理解。通常情况下,代码块里会包含一些指令或者逻辑,用来处理数据或者实现特定的功能。

如果你看到这样的代码块,通常意味着这里有一些需要特别注意的代码,可能是示例代码或者是某个功能的实现。

记住,理解代码的关键在于多练习和多尝试,慢慢你就会对这些内容变得熟悉。

4

试试这个。

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
13

为什么不直接用简单的正则表达式呢:

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

# result '_one_world_is_not_enough_to_live'

撰写回答