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.
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):
return "".join(x.capitalize() for x in snake_str.lower().split("_"))
def to_lower_camel_case(snake_str):
# We capitalize the first letter of each component except the first one
# with the 'capitalize' method and join them together.
camel_string = to_camel_case(snake_str)
return snake_str[0].lower() + camel_string[1:]
Example:
In [11]: to_lower_camel_case('snake_case')
Out[11]: 'snakeCase'
In [12]: to_lower_camel_case('SNAKE_Case')
Out[12]: 'snakeCase'
In [13]: to_lower_camel_case('SNAKE_CASE')
Out[13]: 'snakeCase'