0

I wrote a python function that should accept a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased.
E.g.: to_weird_case('Weird string case') # => returns 'WeIrD StRiNg CaSe'

def to_weird_case(string):
    s = list(string.split(" "))
    words = []
    for word in s:
        w = map(lambda x: x.upper() if word.index(x)%2 == 0 else x.lower(), word)
        w = "".join(list(w))
        words.append(w)

    #print(words)
    return " ".join(words)

Now to my problem: As soon as more than one word is passed, the last letters of the last word are all converted to uppercase and I don't understand why...
E.g.: to_weird_case('This is a testii') returns ThIs Is A TeSTII

Thanks for help

1
  • 1
    word.index doesn't find the index of the letter you're currently looking at, it finds the index of the first occurrence of that characters within the string… Commented Jan 9, 2020 at 11:25

1 Answer 1

2

This is because the index() function returns the index of the first instance of that character in a string. What you want is to write your loop using enumerate:

for index, word in enumerate(s):

With this, rather than use the index function, you can write your logic based on the index variable passed from enumerate().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.