Tunahan
Tunahan

Reputation: 21

Making every second letter in a string uppercase with a method other than index() in Python?

def myfunc(mylist = str):
mystring = ''
for x in mylist:
    if mylist.index(x) % 2 == 0:
        mystring = mystring + x.lower()
    else:
        mystring = mystring + x.upper()
return mystring
print(myfunc('committee')) #Doesn't work
print(myfunc('ilovehoney')) #Does work

I believe the mistake in my code is the index() since it does not recognize repeating letters in the string. Does anyone know of a different method I could use? The output in the first example is 'cOmmiTTEE' but should be 'cOmMiTtEe' while the output in the second example is as I intended 'iLoVeHoNeY'. Though I am not sure why my function suddenly works in the second example. Thanks for the help.

Upvotes: 2

Views: 2394

Answers (3)

VPfB
VPfB

Reputation: 17342

You don't need to know the exact index at all. Just flip a flag: no-yes-no-yes-no-etc.

def myfunc(mylist):
    mystring = ''
    upper = False
    for x in mylist:
        mystring = mystring + (x.upper() if upper else x.lower())
        upper = not upper
    return mystring

Please note that it is inefficient to construct a string that way (give "Shlemiel the painter" to google). Improved version:

def myfunc(mylist):
    mychars = []
    upper = False
    for x in mylist:
        mychars.append(x.upper() if upper else x.lower())
        upper = not upper
    return ''.join(mychars)

Upvotes: 2

Andreas
Andreas

Reputation: 9207

enumerate() gives you the index of the current loop:

s = 'committee'
"".join([x.upper() if i%2!=0 else x for i,x in enumerate(s)])
Out[4]: 'cOmMiTtEe'

Upvotes: 3

m_dubya
m_dubya

Reputation: 111

You can use enumerate to get the index and value from an iterable:

for idx, x in enumerate(mylist):
    if idx % 2 == 0:
        mystring = mystring + x.lower()
    else:
        mystring = mystring + x.upper()

Upvotes: 2

Related Questions