Skip to content
Related Articles

Related Articles

Python | Selective casing in String

View Discussion
Improve Article
Save Article
  • Last Updated : 03 Aug, 2022
View Discussion
Improve Article
Save Article

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. 

Python3




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

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. 

Python3




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

Output : 

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

Method #3 : Using replace() method 

Python3




# Python3 code to demonstrate working of
# Selective casing in String
 
# 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
for i in chg_list:
    test_str=test_str.replace(i,i.upper())
 
# printing result
print("String after Selective casing : " + test_str)

Output

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!