[Python] Python - Convert string to CamelCase

Discussão em 'Python' iniciado por Stack, Abril 2, 2025.

  1. Stack

    Stack Membro Participativo

    I coded the following method to convert a string to Camel Case. However, it doesn't work when the string starts with a space.

    def CamelCase(s):

    newString = ''
    newString += s[0].upper()

    for k in range(1, len(s)):
    if s[k] == ' ':
    newString += s[k + 1].upper()
    k += 1
    elif s[k - 1] != ' ':
    newString += s[k]
    return newString


    The input is: " I love chocolate." And the output should be: "ILoveChocolate."

    But it gives the following error:

    IndexError Traceback (most recent call last)
    <ipython-input-13-28f7ddba2ba2> in <module>
    ----> 1 print(CamelCase(" Algoritmos y estructuras de datos "))

    <ipython-input-12-29aa8012fb61> in CamelCase(s)
    9 for k in range(1, len(s)):
    10 if s[k] == ' ':
    ---> 11 nuevaCadena += s[k + 1].upper()
    12 k += 1
    13 elif s[k - 1] != ' ':

    IndexError: string index out of range


    Help?

    Continue reading...

Compartilhe esta Página