Python 将 Snake Case 转换为 Lower Camel Case (lowerCamelCase)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19053707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:38:56  来源:igfitidea点击:

Converting Snake Case to Lower Camel Case (lowerCamelCase)

pythonpython-2.7

提问by luca

What would be a good way to convert from snake case (my_string) to lower camel case (myString) in Python 2.7?

my_string在 Python 2.7 中将蛇形 ( )转换为小驼峰 (myString)的好方法是什么?

The obvious solution is to split by underscore, capitalize each word except the first one and join back together.

显而易见的解决方案是用下划线分割,将除第一个之外的每个单词大写,然后重新连接在一起。

However, I'm curious as to other, more idiomatic solutions or a way to use RegExpto achieve this (with some case modifier?)

但是,我很好奇其他更惯用的解决方案或RegExp用于实现此目的的方法(使用某种大小写修饰符?)

采纳答案by jbaiter

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:])

Example:

例子:

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

回答by Leon Young

>>> snake_case = "this_is_a_snake_case_string"
>>> l = snake_case.split("_")
>>> print l[0] + "".join(map(str.capitalize, l[1:]))
'thisIsASnakeCaseString'

回答by Simeon Visser

Obligatory one-liner:

强制性单线:

import string

def to_camel_case(s):
    return s[0].lower() + string.capwords(s, sep='_').replace('_', '')[1:] if s else s

回答by steve

another one liner

另一个班轮

def to_camel_case(snake_string):
    return snake_string.title().replace("_", "")

回答by MLev

Building on Steve's answer, this version should work:

基于史蒂夫的回答,这个版本应该可以工作:

def to_camel_case(snake_case_string):
    titleCaseVersion =  snake_case_string.title().replace("_", "")
    camelCaseVersion = titleCaseVersion[0].lower() + titleCaseVersion[1:]
    return camelCaseVersion

回答by Berislav Lopac

Here's yet another take, which works only in Python 3.5 and higher:

这是另一个尝试,仅适用于 Python 3.5 及更高版本:

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

回答by Antoine Pinsard

Here is a solution using regular expressions:

这是使用正则表达式的解决方案:

import re

def snake_to_camel(text):
    return re.sub('_([a-zA-Z0-9])', lambda m: m.group(1).upper(), text)

回答by Chandler Childs

def to_camel_case(snake_str):
    components = snake_str.split('_')
    return reduce(lambda x, y: x + y.title(), components[1:], components[0])

回答by Michael Thiesen

Without using list comprehensions:

不使用列表推导式:

def snake_to_camel_case(text_snake):
    return '{}{}'.format(
        text_snake[:1].lower(),
        text_snake.title().replace('_', '')[1:],
    )

回答by Abraham Hernandez

There is also tocamelcaseto easily convert from snake case to camel case.

tocamelcase可以轻松地从蛇盒转换为骆驼盒。

Install

安装

$ pip install tocamelcase

$ pip install tocamelcase

and then you can use it like this:

然后你可以像这样使用它:

import tocamelcase

print(tocamelcase.convert("non_camel_case"))
# -> non_camel_case → NonCamelCase

There is also decamelizethat is the inverse of this module.

还有就是decamelize这个模块的反面。