'How to print a string in alternating case?
I want to print a string in Python with alternate cases. For example my string is "Python". I want to print it like "PyThOn". How can I do this?
string = "Python"
for i in string:
if (i%2 == 0):
(string[i].upper())
else:
(string[i].lower())
print (string)
Solution 1:[1]
It's simply not Pythonic if you don't manage to work a zip() in there somehow:
string = 'Pythonic'
print(''.join(x + y for x, y in zip(string[0::2].upper(), string[1::2].lower())))
OUTPUT
PyThOnIc
Solution 2:[2]
mystring="Python"
newstring=""
odd=True
for c in mystring:
if odd:
newstring = newstring + c.upper()
else:
newstring = newstring + c.lower()
odd = not odd
print newstring
Solution 3:[3]
For random caps and small characters
>>> def test(x):
... return [(str(s).lower(),str(s).upper())[randint(0,1)] for s in x]
...
>>> print test("Python")
['P', 'Y', 't', 'h', 'o', 'n']
>>> print test("Python")
['P', 'y', 'T', 'h', 'O', 'n']
>>>
>>>
>>> print ''.join(test("Python"))
pYthOn
>>> print ''.join(test("Python"))
PytHon
>>> print ''.join(test("Python"))
PYTHOn
>>> print ''.join(test("Python"))
PytHOn
>>>
For Your problem code is :
st = "Python"
out = ""
for i,x in enumerate(st):
if (i%2 == 0):
out += st[i].upper()
else:
out += st[i].lower()
print out
Solution 4:[4]
Try it:
def upper(word, n):
word = list(word)
for i in range(0, len(word), n):
word[i] = word[i].upper()
return ''.join(word)
Solution 5:[5]
You can iterate using list comprehension, and force case depending on each character's being even or odd.
example:
s = "This is a test string"
ss = ''.join([x.lower() if i%2 else x.upper() for i,x in enumerate(s)])
print ss
s = "ThisIsATestStringWithoutSpaces"
ss = ''.join([x.lower() if i%2 else x.upper() for i,x in enumerate(s)])
print ss
output:
~/so_test $ python so_test.py
ThIs iS A TeSt sTrInG
ThIsIsAtEsTsTrInGwItHoUtSpAcEs
~/so_test $
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cdlane |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | amarynets |
| Solution 5 | Chris Adams |
