0

I'm trying to create a loop that will take what the user entered and print it back alternating between upper and lowercase. Ex: the user enters 'helloworld', it prints back 'HeLlOwOrLd'. Here's what I have so far (trust me, I know it's not optimal, it's just what I could get to work):

s = input("enter characters: ")
word = ''
count = 0


for i in s:
        up = s[::2]
        up2 = up.upper()
        up3 = up2[0 + count]
        low = s[1::2]
        low2 = low.lower()
        low3 = low2[0 + count]
        word += up3 + low3
        count += 1

print(word)

When I trace it in the debugger, word comes to the right value, and then it runs the loop again, thus getting the index out of range error. Ideas?

1
  • 3
    The two most common problems in programming are cache validation, naming things, and off-by-one errors. Commented Apr 3, 2015 at 0:25

3 Answers 3

2

Your looping through too many times. Your splitting s in half in the loop, but looping once for each character in s.

s = input("enter characters: ")
word = ''


for count in range(len(s[::2])):
        up = s[::2]
        up2 = up.upper()
        up3 = up2[0 + count]
        low = s[1::2]
        low2 = low.lower()
        if(len(low2)>count):
            low3 = low2[0 + count]
        else:
            low3=''
        word += up3 + low3
        count += 1

print(word)

Cheers!

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

2 Comments

Why convert the entire string on each iteration, why do 0 + count and why increment count?
The question asked for help regarding the error. The attempt was to change as little as possible to aide in seeing what caused the error.
2

count will end up equal to the length of s. However, you are using count as an index for strings that are shorter than s, such as up3.

Try the following:

>>> result = ''
>>> word = 'hello'
>>> for i in range(len(word)):
...     result += (word[i].lower() if i%2 else word[i].upper())
...
>>> result
'HeLlO'

Also:

>>> word = 'HellOWorLD'
>>> ''.join(word[i].lower() if i%2 else word[i].upper() for i in range(len(word)))
'HeLlOwOrLd'

Comments

0

You could use the case conversion functions from string and itertools.cycle to vary which one is applied to each character. Wrap that all up in a join statement and you get:

''.join(case(c) for case,c in 
    zip(itertools.cycle((string.upper,string.lower)), 'helloworld'))

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.