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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :



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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

The original string is : geeksforgeeks
The alterate case string is : GeEkSfOrGeEkS


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.