"Replace capital letters in a string with "_小写字母“并打印输出”不起作用

"Replace capital letters in a string with "_lower case letter" and print the output" does not work

由于某些原因,以下代码不起作用。 if 语句的第一部分似乎有效。关于代码有什么问题的任何想法?

sentence_input = str(input())
a = "_"
string = ""
if sentence_input.islower():
    print(sentence_input)
else:
    character_list = list(sentence_input)
    for i in character_list:
        if i.isupper():
            i.replace(i, a + i.lower())
    print(string.join(character_list))

在 else 语句中,您似乎试图用新字符替换该字符。你实际上应该做的是完全替换数组中的元素

试试这个:

sentence_input = str(input())
a = "_"
string = ""
if sentence_input.islower():
    print(sentence_input)
else:
    character_list = list(sentence_input)

    for i, c in enumerate(character_list):
        if c.isupper():
            character_list[i] = "_" + c.lower()
    print(string.join(character_list))