如何简化Python中下划线转驼峰的转换?

41 投票
17 回答
48638 浏览
提问于 2025-04-16 07:45

我写了一个函数,可以把下划线格式的字符串转换成驼峰式命名,首个单词首字母小写,比如把 "get_this_value" 转换成 "getThisValue"。另外,我还需要保留字符串开头和结尾的下划线,以及中间的双下划线(或三下划线等),比如:

"_get__this_value_" -> "_get_ThisValue_".

代码如下:

def underscore_to_camelcase(value):
    output = ""
    first_word_passed = False
    for word in value.split("_"):
        if not word:
            output += "_"
            continue
        if first_word_passed:
            output += word.capitalize()
        else:
            output += word.lower()
        first_word_passed = True
    return output

虽然上面的代码能正常工作,但我觉得它写得不够简洁,感觉有点不符合 Python 的风格。所以我想找一些方法来简化代码,比如使用列表推导式等等。

17 个回答

25

我个人比较喜欢使用正则表达式。这是一个对我来说很有效的正则表达式:

import re
def to_camelcase(s):
    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s)

使用了unutbu的测试:

tests = [('get__this_value', 'get_ThisValue'),
         ('_get__this_value', '_get_ThisValue'),
         ('_get__this_value_', '_get_ThisValue_'),
         ('get_this_value', 'getThisValue'),
         ('get__this__value', 'get_This_Value')]

for test, expected in tests:
    assert to_camelcase(test) == expected
67

这个方法可以用,但第一个单词还是小写的。

def convert(word):
    return ''.join(x.capitalize() or '_' for x in word.split('_'))

(我知道这不是你问的具体内容,而且这个讨论已经很久了,但因为在谷歌搜索这种转换时它很常见,所以我想分享我的解决方案,也许能帮到其他人。)

33

你的代码没问题。我觉得你想解决的问题是 if first_word_passed 看起来有点别扭。

解决这个问题的一种方法是使用生成器。我们可以很简单地让它在第一次调用时返回一个东西,而在后续调用时返回另一个东西。因为Python支持一等函数,我们可以让生成器返回我们想用来处理每个单词的函数。

接下来,我们只需要使用条件运算符,这样就能在列表推导式中处理由双下划线返回的空值。

所以如果我们有一个单词,就调用生成器来获取设置大小写的函数;如果没有单词,我们就用 _,这样生成器就不会被改变。

def underscore_to_camelcase(value):
    def camelcase(): 
        yield str.lower
        while True:
            yield str.capitalize

    c = camelcase()
    return "".join(c.next()(x) if x else '_' for x in value.split("_"))

撰写回答