I am trying to loop though a string and convert underscores to camel case. Example) my_string --> myString
I have posted my working code below. Can someone help me figure out the hole in my logic?
def to_camel_ca (string):
camel_string = ""
for i in range(len(string)):
if string[i] == '_':
camel_string = camel_string string[i 1].replace(string[i 1], string[i 1].capitalize())
elif string[i] != "_":
camel_string = camel_string string[i]
print(camel_string)
return camel_string
to_camel_ca('my_string')
#returns
m
my
myS
mySs
mySst
mySstr
mySstri
mySstrin
mySstring
'mySstring'
Many thanks!
CodePudding user response:
Notice that the camelCase string will be shorter. When you encounter an underscore, and capitalize the next letter, you need to skip a letter in the source string. Here is a way to do that:
def to_camel_ca (string):
camel_string = ""
skip = False
for i in range(len(string)):
if skip:
skip = False
continue
if string[i] == '_':
camel_string = camel_string string[i 1].replace(string[i 1], string[i 1].capitalize())
skip = True
elif string[i] != "_":
camel_string = camel_string string[i]
print(camel_string)
return camel_string
Example
to_camel_ca('my_test_string')
m my myT myTe myTes myTest myTestS myTestSt myTestStr myTestStri myTestStrin myTestString
A Slightly Different Approach
Here's is a slightly simpler approach. When an underscore is encountered, make a note to capitalize the next letter. It has the advantage of handling input strings which end in underscore.
def to_camel_ca (string):
camel_string = ""
capitalize = False
for i in range(len(string)):
if string[i] == '_':
capitalize = True
continue
elif capitalize:
camel_string = camel_string string[i].capitalize()
capitalize = False
elif string[i] != "_":
camel_string = camel_string string[i]
print(camel_string)
return camel_string
CodePudding user response:
The problem is that a character after an underscore is processed/added to the camelString twice: one when the if finds and underscore and again when that character itself matches the elif condition.
