Dan A
Dan A

Reputation: 414

Python Lowercase and Uppercase String

Is there a way to convert a string to a sequence of uppercase and lowercase letters?

For example, "Kilometers" → "KiLoMeTeRs".

Upvotes: 2

Views: 1657

Answers (2)

Selcuk
Selcuk

Reputation: 59445

A more esoteric way:

>>> a = 'Kilometers'
>>> "".join("".join(i) for i in zip(a[::2].upper(), a[1::2].lower()))
'KiLoMeTeRs'

or using @lenik's more concise form:

>>> "".join(a+b for a, b in zip(a[::2].upper(), a[1::2].lower()))

Upvotes: 2

SimonR
SimonR

Reputation: 1824

a = 'Kilometers'

print(''.join([char.upper() if i%2==0 else char.lower() for i, char in enumerate(a)]))

result = 'KiLoMeTeRs'

Upvotes: 6

Related Questions