将Snake Case转换为Lower camelcase(lowerCamelCase)

2024-05-14 23:56:14 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2.7中,将snake case(my_string)转换为lower camel case(myString)的好方法是什么?

最明显的解决方案是用下划线分隔,将除第一个单词外的每个单词大写并重新连接在一起。

但是,我很好奇其他更习惯的解决方案或使用RegExp来实现这一点的方法(使用一些case修饰符?)


Tags: 方法stringmy解决方案修饰符单词lowercase
3条回答

下面是另一个take,它只适用于Python3.5及更高版本:

def camel(snake_str):
    first, *others = snake_str.split('_')
    return ''.join([first.lower(), *map(str.title, others)])

强制性一行:

import string

def to_camel_case(s):
    return s[0].lower() + string.capwords(s, sep='_').replace('_', '')[1:] if s else s
def to_camel_case(snake_str):
    components = snake_str.split('_')
    # We capitalize the first letter of each component except the first one
    # with the 'title' method and join them together.
    return components[0] + ''.join(x.title() for x in components[1:])

示例:

In [11]: to_camel_case('snake_case')
Out[11]: 'snakeCase'

相关问题 更多 >

    热门问题