Skip to content Skip to sidebar Skip to footer

Python Alternate Cases

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?

Solution 1:

You can try the spongemock library!

Alternatively, if you'd like to capitalise every other letter, then check out this question.

Solution 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:

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 4:

For random caps and small characters

>>> deftest(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 5:

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)

Post a Comment for "Python Alternate Cases"