Search code examples
pythonloopsiterationcamelcasing

Splitting a word at the uppercase without using regex or a function leads to error cannot assign the expression or not enough value to unpack


I am trying to learn python. In this context I need to split a word when encountering an upper case, convert it as a lower case and then insert a "_".

I have seen various quite complex answer here or here or here, but I am trying to do it as simply as possible.

So far, here is my code:

word = input("What is the camelCase?")

for i , k in word:
    if i.isupper() and k.islower():
        word2 = k + "_" + i.lower + k
        print(word2)
    else:
        print(word)

This leads to "not enough values to unpack (expected 2, got 1)" after I input my word.

Another attempt here:

word = input("What is the camelCase?")

for i and k in word:
    if i.isupper() and k.islower():
        word2 = k + "_" + i.lower + k
        print(word2)
    else:
        print(word)

In this case I cannot even write my word, I directly have the error: "cannot assign to expression"


Solution

  • Try it this way.

    a=input("enter word:")
    b=""
    for i in a:
        if i.isupper():
            b=b+(i.lower()+"_")
        else:b=b+i
    print(b)
    

    Hope it helped :)