Python | Selective casing in String

Sometimes, while working with Python, we can have a problem in which we need to perform the case change of certain characters in string. This kind of problem can come in many types of applications. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using enumerate() + loop + upper()
This problem can be solved using set of above functionalities. This is brute force way to perform this task, in this we iterate through each element in string and change to uppercase if it’s present in case change list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Selective casing in String
# using loop + upper() + enumerate()
  
# initialize string
test_str = 'gfg is best'
  
# printing original string 
print("The original string : " + str(test_str))
  
# initialize change case list 
chg_list = ['g', 'f', 's']
  
# Selective casing in String
# using loop + upper() + enumerate()
res = list(test_str)
for idx, char in enumerate(res):
    if char in chg_list:
        res[idx] = char.upper()
  
# printing result
print("String after Selective casing : " + str(''.join(res)))

chevron_right


Output :

The original string : gfg is best
String after Selective casing : GFG iS beSt

&nsbp;

Method #2 : Using list comprehension + upper() + join()
This is shorthand version in which this problem can be solved. In this, we perform similar task in similar way as above method but in one-liner way using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Selective casing in String
# using list comprehension + upper() + join()
  
# initialize string
test_str = 'gfg is best'
  
# printing original string 
print("The original string : " + str(test_str))
  
# initialize change case list 
chg_list = ['g', 'f', 's']
  
# Selective casing in String
# using list comprehension + upper() + join()
res = ''.join([char.upper() if char in chg_list
                else char for char in test_str])
  
# printing result
print("String after Selective casing : " + str(''.join(res)))

chevron_right


Output :

The original string : gfg is best
String after Selective casing : GFG iS beSt



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.