Python | Alternate cases in String
The problem of case changes a string is quite common and has been discussed many times. Sometimes, we might have a problem like this in which we need to convert the odd character of string to upper case and even positioned characters to lowercase. Let’s discuss certain ways in which this can be performed.
Method #1 : Using upper() + lower() + loop
This task can be performed in brute force method in a way that we iterate through the string and convert odd elements to uppercase and even to lower case using upper() and lower() respectively.
# Python3 code to demonstrate working of # Alternate cases in String # Using upper() + lower() + loop # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # Using upper() + lower() + loop # Alternate cases in String res = "" for idx in range(len(test_str)): if not idx % 2 : res = res + test_str[idx].upper() else: res = res + test_str[idx].lower() # printing result print("The alterate case string is : " + str(res)) |
The original string is : geeksforgeeks The alterate case string is : GeEkSfOrGeEkS
Method #2 : Using list comprehension
This is the shortened one liner approach to this problem. It uses same logic as above but in much more compact way.
# Python3 code to demonstrate working of # Alternate cases in String # Using list comprehension # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # Using list comprehension # Alternate cases in String res = [ele.upper() if not idx % 2 else ele.lower() for idx, ele in enumerate(test_str)] res = "".join(res) # printing result print("The alterate case string is : " + str(res)) |
The original string is : geeksforgeeks The alterate case string is : GeEkSfOrGeEkS
Recommended Posts:
- Python | Convert string list into multiple cases
- Python | Alternate Sort in String list
- Python | Alternate vowels and consonents in String
- Python - Convert Alternate String Character to Integer
- Useful cases to illustrate Decorators in python
- Python - Details of CoronaVirus cases in various countries
- Get Corona cases details - Python PyQt5
- Corona Virus cases of various countries - Using Python PyQt
- Python - Get Confirmed, Recovered, Deaths cases of Corona around the globe
- Python - Alternate Default Key Value
- Python | Alternate Cycling in list
- Python | Alternate character addition
- Python | Alternate Rear iteration
- Python | Alternate front - rear Sum
- Python | List Initialization with alternate 0s and 1s
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

