Sujet : Re: Flubbed it in the second interation through the string: range error... HOW?
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 29. May 2024, 19:09:07
Autres entêtes
Organisation : Stefan Ram
Message-ID : <uppercase-20240529190808@ram.dialup.fu-berlin.de>
References : 1 2 3 4 5
MRAB <
python@mrabarnett.plus.com> wrote or quoted:
Small mistake there. The original code converted to uppercase on even
indexes, whereas your code does it on odd ones.
Here follows my humble effort.
import doctest
def alternate_uppercase( s ):
"""
Alternates the case of alphabetic characters in a given string.
Args:
s (str): The input string.
Returns:
str: The string with alternating uppercase and lowercase letters.
Examples:
>>> alternate_uppercase( 'Python is awesome!' )
'PyThOn Is AwEsOmE!'
>>> alternate_uppercase( 'ab,c,,d,,,e,,,,f' )
'Ab,C,,d,,,E,,,,f'
>>> alternate_uppercase( '' )
''
"""
result =[ None ]* len( s )
letter_count = 0
for char_pos, char in enumerate( s ):
if char.isalpha():
result[ char_pos ]=\
( char.lower if letter_count%2 else char.upper )()
letter_count += 1
else:
result[ char_pos ]= char
return ''.join( result )
doctest.testmod()