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

Python下划线/短横线分隔字符串转驼峰(禁用re正则库)

问题说明

实现字符串转驼峰命名的函数,要求如下:

  • 输入字符串仅以下划线_、短横线-作为单词分隔符,例如the_big_red_apple、the-big-red-apple
  • 转换后为驼峰格式:除首单词外,其余单词首字母大写,无分隔符
  • 特殊规则:原字符串首单词首字母为大写时,转换后保留首字母大写(大驼峰);首字母为小写时,转换后首字母保持小写(小驼峰)
  • 限制:不允许使用re正则库
实现思路

不依赖正则的处理逻辑非常直接:

  1. 先把所有短横线-替换为下划线_,统一分隔符,避免多分隔符重复判断
  2. 按下划线拆分字符串得到单词列表,过滤连续分隔符产生的空字符串
  3. 单独处理第一个单词的大小写,匹配原字符串首字母的大小写规则
  4. 从第二个单词开始,每个单词统一做首字母大写、其余字符小写的处理,依次拼接即可
  5. 补充空输入的边界判断,避免索引报错
完整实现代码
def to_camel_case(text):
    # 处理空输入边界
    if not text:
        return ""
    # 统一分隔符后拆分单词,过滤空串兼容连续分隔符场景
    words = text.replace("-", "_").split("_")
    words = [word for word in words if word]
    # 匹配原首字母大小写处理第一个单词
    if text[0].isupper():
        res = words[0].capitalize()
    else:
        res = words[0].lower()
    # 拼接后续单词,每个单词首字母大写
    for word in words[1:]:
        res += word.capitalize()
    return res
效果验证
# 测试用例
print(to_camel_case("the_big_red_apple"))  # 输出 theBigRedApple
print(to_camel_case("The-big-red-apple"))  # 输出 TheBigRedApple
print(to_camel_case("a__b--c"))            # 输出 aBC
print(to_camel_case("A-B-C"))              # 输出 ABC
print(to_camel_case(""))                   # 输出 空字符串

注:原实现中return print(text)写法有误,print()函数返回值为None,函数需要直接返回转换后的字符串结果,不需要嵌套print。

内容的提问来源于stack exchange,提问作者Daniel Dubinko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 12:57:18