How can I convert snake_case to camelCase (and vice versa) in Python?

4

How can I convert a string pythonic to snake_case in%% possible?

Example:

  snake1 = 'minha_string_snake_case' # minhaStringSnakeCase
  snake2 = '_teste_string' #  _TestString
    
asked by anonymous 03.07.2015 / 13:53

3 answers

2

A simpler version would be to use regular expression from the beginning. In the re module there is the sub() function that allows you to make substitutions within a string using regular expressions.

More than that, re.sub() allows you to pass a function to process the pattern found and return a string for the substitution, which fits nicely in your case.

Logo:

>>> import re

For camelCase:

>>> camel = re.sub(r'[a-zA-Z]_([a-zA-Z])',
...                lambda _ : _.group(0)[0] + _.group(1).upper(),
...                '_para_camel_case')
>>> camel
'_paraCamelCase'

For snake_case:

>>> snake = re.sub('[A-Z]',
...                lambda _ : '_' +  _.group(0).lower(),
...                '_paraSnakeCase')
>>> snake
'_para_snake_case'

There may be more appropriate regular expressions, but that's for you.

    
03.07.2015 / 22:57
1
One way to do this is by working with list comprehensions and join , as in the example below:

import itertools

def flatten(lista):
    return list(itertools.chain(*lista))

def converte_para_camel_string(valor):
    valor = valor.split('_')
    if valor[0] == '':
        valor[0] = '_'
    ret = [valor[0]]
    ret.append([x.capitalize() for x in valor[1:]])
    ret = flatten(ret)
    return ''.join(ret)

and you will get the following result:

snake1 = converte_para_camel_string('minha_string_snake_case') # minhaStringSnakeCase
snake2 = converte_para_camel_string('_teste_string') #  _TestString

Already to convert from camel case to snake, you can use regular expressions as follows: / p>

import re

def converte_para_snake_string(valor):
    valor = re.findall('[A-Z]*[^A-Z]*', valor) # dá um split nas letras maiúsculas
    if valor[0] == '_':
        valor[0] = ''
    valor = [x.lower() for x in valor]
    return '_'.join(valor)[:-1]

This will return:

string1 = converte_para_snake_string('testeString') #teste_string
string2 = converte_para_snake_string('_TesteString') #_teste_string
    
03.07.2015 / 14:23
1

To convert to CamelCase, simply break the string in "_" and capitalize the first letter - and this can be done in a single reasonably readable expression (without the need to declare function, or itertools methods):

CamelCase = "".join(word.capitalize() for word in snake_case.split("_"))

If you need the first letter to be lowercase, you can either follow the above expression with a simple readable CamelCase = CamelCase[0].lower() + CamerlCase[1:] , u put a counter and an if inine on the first expression to not capitalize the first word:

CamelCase = "".join((word.capitalize() if i else word)for i, word in enumerate(snake_case.split("_")))

To go back, it is necessary to process letter by letter, but can also be done in a single expression:

 snake_case = "".join(("_" + letter.lower()) if letter.isupper() else letter for letter in CamelCase).strip("_")
    
04.07.2015 / 09:09