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?)
Advertisement
Answer
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'