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

Python字符串转snakecase格式实现及多余下划线问题解决

问题原因
  • 语法错误:普通函数内部误用self关键字,函数接收的参数名是string,但替换和返回时都调用了不存在的self.string;另外测试代码里调用的函数名toSnakeCaseV1和实际定义的toSnakeCase不一致。
  • 首尾下划线的核心成因:正则[^a-zA-Z]会匹配字符串首尾位置的非字母字符(比如测试用例里开头结尾的-、.),统一替换为空格后转下划线,就会生成首尾多余的下划线。
  • 逻辑错误:正则替换后的结果保存在局部变量string里,但返回时没有用这个处理后的值,反而调用了未定义的self.string,且多余使用''.join()处理字符串。
修复方案

在替换完成后用strip('_')清除首尾的下划线,同时修正语法和逻辑错误,调整后的代码如下:

import re

def to_snake_case(string, rest_to_lower: bool = True):
    # 把驼峰分界、非字母字符都替换为下划线
    processed = re.sub(r'(?:(?<=[a-z])(?=[A-Z]))|[^a-zA-Z]', '_', string)
    # 清除首尾多余下划线,统一转小写(默认开启)
    processed = processed.strip('_')
    return processed.lower() if rest_to_lower else processed
测试验证

用给出的测试用例运行:

strings = ['hello world', 'HelloWorld', '-HELLO-WORLD-', 'Hello-World', 'hello_world', '--hello.world', 'Hello-WORLD', 'helloWORLD']

for i, j in enumerate(strings, 1):
    print(f'{i}. {to_snake_case(j)}')

输出完全符合预期:

1. hello_world
2. hello_world
3. hello_world
4. hello_world
5. hello_world
6. hello_world
7. hello_world
8. hello_world

内容的提问来源于stack exchange,提问作者Kunal Tanwar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:48:02