You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让驼峰命名转换函数兼容空字符串?解决索引越界异常

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 == None check: Your function receives an empty string, not None, 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:

  1. Empty Input Safety: The if not text: check catches empty strings (and other falsy values like None) and returns an empty string right away, so we never reach the text[0] line when there's nothing to access.
  2. 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.
  3. 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.
  4. Straightforward Case Adjustment: Instead of creating a separate small variable, we directly replace the first character of the capitalized result with the original first_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') returns helloWorld (keeps the original lowercase first character).
  • Underscore-separated input: to_camel_case('Hello_World') returns HelloWorld (keeps the original uppercase first character).

内容的提问来源于stack exchange,提问作者chico-ocholoco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:00:43