Skip to content
Related Articles

Related Articles

Improve Article

Python | Selective casing in String

  • Last Updated : 29 Nov, 2019

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :