0

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)
TylerH
  • 20,799
  • 66
  • 75
  • 101
Twinkle Sahni
  • 11
  • 1
  • 2

5 Answers5

2

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
cdlane
  • 40,441
  • 5
  • 32
  • 81
1
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
PressingOnAlways
  • 11,948
  • 6
  • 32
  • 59
  • This won't account for spaces in `mystring` – Cuber Aug 31 '17 at 04:25
  • The example did not have spaces nor is it defined that every word is to start with a capital letter. Though if you want to have the first letter always start capitalized, it would be as simple as adding a `if c == ' '; odd = True`. – PressingOnAlways Aug 31 '17 at 04:34
1

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
Kallz
  • 3,244
  • 1
  • 20
  • 38
0

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)
amarynets
  • 1,765
  • 10
  • 27
0

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 $
Chris Adams
  • 1,067
  • 8
  • 15
  • This is the best answer. You can also just put the generator inside the `join` (rather than forming a list as well), like so: `''.join(x.upper() if i % 2 else x.lower() for i, x in enumerate(s))` – teepee Nov 10 '20 at 17:54