将Snake Case转换为更低的Camel Case(lowerCamelCase)

luc*_*uca 64 python python-2.7

my_string在Python 2.7中从snake case()转换为较低的camel case(myString)的好方法是什么?

显而易见的解决方案是通过下划线拆分,将除第一个单词之外的每个单词大写并重新连接在一起.

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

jba*_*ter 113

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:])
Run Code Online (Sandbox Code Playgroud)

例:

In [11]: to_camel_case('snake_case')
Out[11]: 'snakeCase'
Run Code Online (Sandbox Code Playgroud)

  • 嗯,这不是真正惯用的Python,它通常遵循"更容易请求宽恕而非许可"的原则.如果你想要类型安全,你可以添加类型提示,但是你可以使用if-else进行类型检查,以便像这样明确的功能(除了字符串之外还有什么其他的可能是camelCase?)只是糟糕的风格和过度的我书中的冗长. (20认同)
  • 还有什么其他datataypes可以适用于? (11认同)
  • 只是想在这里第二个jbaiter.`to_camel_case`不负责确保输入是一个字符串,它是调用代码的责任.传递非字符串会引发异常,这很好.这就是例外情况. (2认同)
  • 有点极端的情况,但如果您希望 `_bar` 变成 `bar` 而不是 `Bar`,那么请稍微调整一下: `components = Snake_str.lstrip('_').split('_')` (2认同)

小智 13

另一艘班轮

def to_camel_case(snake_string):
    return snake_string.title().replace("_", "")
Run Code Online (Sandbox Code Playgroud)

  • 第一个字符是大写。 (8认同)

Ber*_*pac 11

这是另一个需要,仅适用于Python 3.5:

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

  • 您是完全正确的,但是在这种情况下并不适用,因为传递给join方法的不是理解而是常规列表。如果要避免创建一个内存列表,可以使用`itertools.chain`,但是如果在将蛇转换为骆驼的情况下担心内存占用,则会遇到更大的问题。;-) (2认同)

小智 7

有点晚了,但几天前我在 /r/python 上发现了这个:

pip install pyhumps
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

import humps

humps.camelize('jack_in_the_box')  # jackInTheBox
# or
humps.decamelize('rubyTuesdays')  # ruby_tuesdays
# or
humps.pascalize('red_robin')  # RedRobin
Run Code Online (Sandbox Code Playgroud)


Sim*_*ser 6

强制性单行:

import string

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

  • 甚至更短:`return re.sub(r'_([az])',lambda x:x.group(1).upper(),name)`[(见这里)](http://rodic.fr /博客/驼峰和 - snake_case串转换与 - 蟒/) (3认同)

Leo*_*ung 5

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