Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace all characters with condition [Python]

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading