Reputation: 11
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)
Upvotes: 0
Views: 7974
Reputation: 27008
You can make good use of cycle from itertools for this problem as follows:
from itertools import cycle
def alternate(s: str) -> str:
f = cycle((str.upper, str.lower))
r = ""
for c in s:
if c.isspace():
r += c
else:
r += next(f)(c)
return r
if __name__ == "__main__":
s = input("Please enter some text: ")
print(alternate(s))
Upvotes: 0
Reputation: 41872
It's simply not Pythonic if you don't manage to include a zip()
in there somehow:
from itertools import zip_longest
string = 'Pythonics'
print(''.join(x + y for x, y in zip_longest(string[0::2].upper(), string[1::2].lower(), fillvalue='')))
OUTPUT
PyThOnIcS
Upvotes: 1
Reputation: 3523
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
Upvotes: 1
Reputation: 12356
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
Upvotes: 1
Reputation: 1097
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 $
Upvotes: 0
Reputation: 1815
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)
Upvotes: 0