Can someone explain to me why this second method does not completely update the string?

I am trying to write a function that converts under_score_words to camelCaseWords. Next, as I would have done something like this in the past,

functionName = "function_for_test_case"
for character in functionName:
    if character == "_":
        functionName = functionName.replace("_" + functionName[functionName.index(character) + 1], functionName[functionName.index(character) + 1].upper())

print functionName

which correctly outputs:

functionForTestCase

However, this time I initially tried to do it differently, which I found a little neat:

functionName = "function_for_test_case"
for index, character in enumerate(functionName):
    if character == "_":
        functionName = functionName.replace("_" + functionName[index + 1], functionName[index + 1].upper())

print functionName

Instead, it displays:

functionFor_test_case

I was shocked at why it didn’t work ... I figured it could be, since I changed the length of the string (by removing the underscore), but then I'm not sure why the first method works.

Also, if you print a replacement as it goes for the second function, you can see that it does find and replace the remaining values, but of course it does not save them. For instance:

functionName = "function_for_test_case"
for index, character in enumerate(functionName):
    if character == "_":
        print functionName.replace("_" + functionName[index + 1], functionName[index + 1].upper())


functionFor_test_case
function_forTest_case
function_for_testCase

, , , - , ?

: for, ,

+4
2

enumerate(functionName) . , 2 1 (_f -> F), . - :

index == 12
character == '_'
functionName == 'functionFor_test_case'
functionName[index + 1] == 'e'

, _e E, .

BTW, camelize() .

+4

, , , ( "_" ) , . , . , ,

# you have already assessed that the character is '_' by the if
i = functionName.find('_')
# your iteration had found another underscore, but by using index() here
# you have ignored anything else, so is equivalent to just checking the
# return of index() or find()
while i >= 0:
    functionName = functionName.replace(
        "_" + functionName[functionName.index(character) + 1], 
        functionName[functionName.index(character) + 1].upper())
    i = functionName.find('_')

# split on all the underscores
parts = functionName.split("_")
# then join - unchanged first word and capitalised rest
out = ''.join(
             [parts[0]] + [w.capitalize() for w in parts[1:]]
             )

, , iPad.

0

Source: https://habr.com/ru/post/1693169/


All Articles