如何让驼峰命名转换函数兼容空字符串?解决索引越界异常
Fixing the IndexError for Empty Strings in Your Camel Case Function
Got it, let's work through this issue step by step—you're totally right about the root cause: when passing an empty string '', trying to access text[0] throws an IndexError because there's no character at that position. We'll fix this while keeping your core logic of preserving the original first character's case fully intact.
Key Adjustments Needed:
- Handle empty input upfront: Before trying to access any character in the string, check if it's empty and return immediately to avoid the index error.
- Remove the redundant
text == Nonecheck: Your function receives an empty string, notNone, so this condition never triggers and can be removed. - Simplify redundant variable logic: We can clean up some extra variables without losing functionality.
Revised Working Code:
import re def to_camel_case(text): # Catch empty input first to prevent index errors if not text: return '' # Preserve the original first character as required first_char = text[0] # Split text by dashes/underscores, then capitalize each segment split_parts = re.split('[-_]', text) capitalized_ans = ''.join(part.title() for part in split_parts) # Ensure the first character matches the original case if capitalized_ans[0] != first_char: return first_char + capitalized_ans[1:] else: return capitalized_ans
Let's Break Down the Changes:
- Empty Input Safety: The
if not text:check catches empty strings (and other falsy values likeNone) and returns an empty string right away, so we never reach thetext[0]line when there's nothing to access. - Preserved Core Logic: We still grab the original first character, but only after confirming the string isn't empty—so this line is now safe.
- Cleaner String Construction: Using
''.join(part.title() for part in split_parts)is a more concise way to build the capitalized string, but it does exactly the same work as your original loop. - Straightforward Case Adjustment: Instead of creating a separate
smallvariable, we directly replace the first character of the capitalized result with the originalfirst_char—this keeps the logic clear and true to your original intent.
Test It Out:
- Empty string:
to_camel_case('')returns''without any errors. - Dash-separated input:
to_camel_case('hello-world')returnshelloWorld(keeps the original lowercase first character). - Underscore-separated input:
to_camel_case('Hello_World')returnsHelloWorld(keeps the original uppercase first character).
内容的提问来源于stack exchange,提问作者chico-ocholoco
相关产品推荐
相关产品推荐

