Home > Blockchain >  How to replace all characters with condition [Python]
How to replace all characters with condition [Python]

Time:05-08

Here is my code to replace a camelCase input with 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)

And with the input userName , it outputs user_name. But with the input with more than two Capital characters, for example, goodUserName only outputs goodUser_name. Please help me find the logic behind this! Thank you!

CodePudding user response:

Don't modify the string in place. Instead, just create a new string:

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

Or, in one line:

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