如何用条件 [Python] 替换所有字符

How to replace all characters with condition [Python]

这是我用 snake_case 替换驼峰式输入的代码:

camel_case = str(input(" "))
snake_case = ""
# check each characters in string
for char in camel_case:
    if char.isupper(): # checking if it is upper or not
        snake_case = camel_case.replace(char, "_"+char.lower())
print(snake_case)

输入userName,输出user_name。但是对于超过两个大写字符的输入,例如 goodUserName 只输出 goodUser_name。请帮我找出这背后的逻辑!谢谢!

不要就地修改字符串。相反,只需创建一个新字符串:

output = ""
for char in camel_case:
    if char.isupper():
        output += "_"
    output += char.lower()

或者,在一行中:

"".join("_"+char.lower() if char.isupper() else char.lower() for char in camel_case)