w3resource

Python: Alternate the case of each letter in a given string and the first letter must be uppercase

Python Basic - 1: Exercise-134 with Solution

Write a Python program to alternate the case of each letter in a given string and the first letter of the said string must be uppercase.

Sample Solution

Python Code:

def test(txt):
    result_str = ""
    s = True
    for i in txt:
        result_str += i.upper() if s else i.lower()
        if i.isalpha():
            s = not s
    return result_str
str1 = "Python Exercises";
print("Original string: ", str1);
print("After alternating the case of each letter of the said string:")
print(test(str1))
str1 = "C# is used to develop web apps, desktop apps, mobile apps, games and much more.";
print("\nOriginal string: ", str1);
print("After alternating the case of each letter of the said string:")
print(test(str1))  

Sample Output:

Original string:  Python Exercises
After alternating the case of each letter of the said string:
PyThOn ExErCiSeS

Original string:  C# is used to develop web apps, desktop apps, mobile apps, games and much more.
After alternating the case of each letter of the said string:
C# iS uSeD tO dEvElOp WeB aPpS, dEsKtOp ApPs, MoBiLe ApPs, GaMeS aNd MuCh MoRe.

Flowchart:

Flowchart: Python - Alternate the case of each letter in a given string and the first letter must be uppercase.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to compute the sum of the negative and positive numbers of an array of integers and display the largest sum.
Next: Write a Python program to get the Least Common Multiple (LCM) of more than two numbers. Take the numbers from a given list of positive integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Python: Tips of the Day

Iterating over dictionaries using 'for' loops:

I am a bit puzzled by the following code: d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] What I don't understand is the key portion. How does Python recognize ...

key is just a variable name.

for key in d:

For Python 3.x:

for key, value in d.items():

For Python 2.x:

for key, value in d.iteritems():

To test for yourself, change the word key to poop.

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems().

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

Ref: https://bit.ly/37dm0Qo