将 Snake Case 转换为 Lower Camel Case (lowerCamelCase) [英] Converting Snake Case to Lower Camel Case (lowerCamelCase)

查看:61
本文介绍了将 Snake Case 转换为 Lower Camel Case (lowerCamelCase)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2.7 中将蛇形大小写 (my_string) 转换为小写字母 (myString) 的好方法是什么?

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

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

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

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

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

推荐答案

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'

这篇关于将 Snake Case 转换为 Lower Camel Case (lowerCamelCase)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆