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

Python实现驼峰式转下划线命名报错问题求助

问题解决与实现方案

两段代码的错误原因

  • 第一段代码:for i , k in word: 写法错误。遍历字符串时每次只能拿到单个字符,你却试图把单个字符拆成i和k两个变量,Python会直接报not enough values to unpack错误。另外代码逻辑也完全没匹配需求,做不到拆分大写字母的效果。
  • 第二段代码:for i and k in word: 是非法语法。and是逻辑判断运算符,不能用来声明循环变量,因此直接触发cannot assign to expression语法错误。

最简单的实现方案

核心逻辑是:遍历每个字符,遇到大写字母时在它前面加下划线并转小写,其他字符直接保留。下面是两种极简写法:

写法1:基础循环(易理解)

word = input("What is the camelCase? ")
result = []
for char in word:
    if char.isupper():
        result.append(f"_{char.lower()}")
    else:
        result.append(char)
# 拼接结果并去掉可能的开头下划线(比如输入为HelloWorld的情况)
final_result = ''.join(result).lstrip('_')
print(final_result)

写法2:列表推导(更简洁)

如果想压缩核心逻辑,可以用列表推导式:

word = input("What is the camelCase? ")
final_result = ''.join([f"_{c.lower()}" if c.isupper() else c for c in word]).lstrip('_')
print(final_result)

测试示例

  • 输入:camelCase → 输出:camel_case
  • 输入:HelloWorldPython → 输出:hello_world_python
  • 输入:CamelCase → 输出:camel_case

内容的提问来源于stack exchange,提问作者Elvino Michel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:37:44