Python中利用循环结合条件语句实现camelCase转snake_case的问题求助
Hey there! Let's work through this camelCase to snake_case conversion problem step by step.
First, let's fix your initial code issue
Your first attempt used return statements inside a loop, which won't work here for two key reasons:
returnis designed to exit a function and return a value—you aren't inside a function here, so this would throw an immediate error.- Even if you were in a function,
returnwould stop the loop on the very first character, which means you'd never process the rest of the input string.
Fixing your list-based approach
Your second code is already on the right track! The only problem is that you're printing the list directly instead of turning it into a single string. Python's str.join() method is perfect for this—it takes all elements in an iterable (like your list) and concatenates them into one continuous string.
Here's how to update your code:
camelCase = input("camelCase: ") snake_case = [] for c in camelCase: if c.islower(): snake_case.append(c) elif c.isupper(): snake_case.append("_" + c.lower()) # Join the list elements into a single string print("snake_case:", ''.join(snake_case))
Now when you input firstName, this will output snake_case: first_name exactly as you need!
Bonus: More concise alternatives
If you want to streamline your code further, here are two handy approaches:
1. Generator expression with join()
You can skip explicitly creating a list and use a generator expression directly inside join():
camel_case = input("camelCase: ") snake_case = ''.join('_' + c.lower() if c.isupper() else c for c in camel_case) print("snake_case:", snake_case)
2. Regular expressions
For a more compact solution (great for complex cases), use re.sub() to replace every uppercase letter with an underscore plus its lowercase equivalent:
import re camel_case = input("camelCase: ") # Replace each uppercase letter with _ + lowercase version, then combine snake_case = re.sub(r'([A-Z])', r'_\1', camel_case).lower() print("snake_case:", snake_case)
内容的提问来源于stack exchange,提问作者Anarres

