Search code examples
pythonpython-2.7replaceenumerate

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


I've been trying to write a function which converts under_score_words to camelCaseWords. The following is how I'd do 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 originally tried doing it another way, which I found a bit neater:

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

Which instead outputs:

functionFor_test_case

I was stumped to why it wasn't working... I figured it might've been since I was changing the length of the string (by removing the underscore), but then I'm not sure why the first method works.

Also, if you print the replace as it goes for the second function, you can see it does actually find and replace the rest of the values, but ofcourse it does not save them. For example:

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

From what I could tell, these functions were essentially doing the same thing in different wording, could anyone explain why they have a different output?

Edit: I'ved edited the for loops to make it more obvious of what I was trying


Solution

  • enumerate(functionName) relies on the original string. The first time you replace 2 chars with just 1 (_f -> F), the indices become invalid. So at some point you have this situation:

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

    So you try to replace _e with E and it's simply not there.

    BTW, take a look at camelize() function in inflection library.