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)
小智 13
另一艘班轮
def to_camel_case(snake_string):
return snake_string.title().replace("_", "")
Run Code Online (Sandbox Code Playgroud)
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)
小智 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)
强制性单行:
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)
>>> 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)
| 归档时间: |
|
| 查看次数: |
28592 次 |
| 最近记录: |