Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert snake_case to lowerCamelCase in Python [duplicate]

Tags:

python

regex

Trying to replace _(character) with just its Uppercase variant. For example:

hello_string_processing_in_python to helloStringProcessingInPython

Since string is immutable in Python, how can string substitution be done efficiently?

ss = 'hello_string_processing_in_python'
for i in re.finditer('_(\w)', ss):
    ????
like image 354
Vivek Kumar Avatar asked Jul 31 '26 00:07

Vivek Kumar


2 Answers

You may try this,

>>> s = "hello_string_processing_in_python"
>>> re.sub(r'_([a-z])', lambda m: m.group(1).upper(), s)
'helloStringProcessingInPython'
like image 180
Avinash Raj Avatar answered Aug 01 '26 13:08

Avinash Raj


No split or regex is needed and it also ensures that the first character is lowercase:

lower_camel_case = ss[0].lower() + ss.title()[1:].replace("_", "")
print(lower_camel_case)

helloStringProcessingInPython
like image 25
Martin Evans Avatar answered Aug 01 '26 15:08

Martin Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!