Python | Selective casing in String
Last Updated :
24 Feb, 2023
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
Time Complexity: O(n)
Auxiliary Space: O(n)
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
Time Complexity: O(n)
Auxiliary Space: O(n)
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)
OutputThe original string : gfg is best
String after Selective casing : GFG iS beSt
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using replace() and index() methods
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
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in chg_list:
test_str = test_str.replace(i, upper[lower.index(i)])
# printing result
print("String after Selective casing : " + test_str)
OutputThe original string : gfg is best
String after Selective casing : GFG iS beSt
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using Regular Expressions
This approach can be useful when you need to change case of multiple characters in a string and you know the pattern of those characters. You can use the re module in Python to perform this task.
Python3
import re
test_str = 'gfg is best'
chg_list = ['g', 'f', 's']
# Compile the regular expression pattern
pattern = '[' + ''.join(chg_list) + ']'
regex = re.compile(pattern)
# Perform the case change
res = regex.sub(lambda x: x.group(0).upper(), test_str)
# Print the result
print("String after Selective casing : " + res)
#This code is contributed by Edula Vinay Kumar Reddy
OutputString after Selective casing : GFG iS beSt
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: using regex()
1.Define the input string 'test_str'.
2.Define a list of characters to change uppercase called 'chg_list'.
3.Use the join() function to concatenate the elements of 'chg_list' using '|' as the separator and store the resulting string in a variable called 'uppercased_chars'.
4.Use the re.sub() function to substitute each character in 'uppercased_chars' with its uppercase equivalent in 'test_str'.
a. The first argument to re.sub() is a regular expression pattern that matches the characters to be substituted.
b. The second argument to re.sub() is a lambda function that takes a single argument (a match object) and returns the replacement string.
c. In the lambda function, use the group() method of the match object to get the matched string, and the upper() method to convert it to uppercase.
5.Store the resulting string in a variable called 'result'.
6.Print the original string using the print() function.
7.Print the resulting string using the print() function.
Python3
import re
test_str = 'gfg is best'
# printing original string
print("The original string : " + str(test_str))
chg_list = ['g', 'f', 's']
uppercased_chars = '|'.join(chg_list)
result = re.sub('[' + uppercased_chars + ']', lambda x: x.group(0).upper(), test_str)
print("String after selective casing: " + result)
#This code is contributed by Jyothi pinjala
OutputThe original string : gfg is best
String after selective casing: GFG iS beSt
Time Complexity:
The join() method has a time complexity of O(n), where n is the number of elements in the list of characters to be uppercased.
The re.sub() method has a time complexity of O(m), where m is the length of the input string.
In the lambda function, the group() method and the upper() method both have a time complexity of O(1).
Therefore, the overall time complexity of the code is O(m+n).
Space Complexity:
The input string 'test_str' occupies O(m) space, where m is the length of the input string.
The 'chg_list' list occupies O(n) space, where n is the number of characters to be uppercased.
The 'uppercased_chars' variable occupies O(n) space.
The re.sub() function and the lambda function do not create any new data structures, and hence their space complexity is O(1).
The resulting string stored in the 'result' variable occupies O(m) space.
Therefore, the overall space complexity of the code is O(m+n).
Similar Reads
Split and Parse a string in Python In this article, we'll look at different ways to split and parse strings in Python. Let's understand this with the help of a basic example:Pythons = "geeks,for,geeks" # Split the string by commas res = s.split(',') # Parse the list and print each element for item in res: print(item)Outputgeeks for g
2 min read
How to Index and Slice Strings in Python? In Python, indexing and slicing are techniques used to access specific characters or parts of a string. Indexing means referring to an element of an iterable by its position whereas slicing is a feature that enables accessing parts of the sequence.Table of ContentIndexing Strings in PythonAccessing
2 min read
Collections.UserString in Python Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: Python3 # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World'
2 min read
Python String replace() Method The replace() method replaces all occurrences of a specified substring in a string and returns a new string without modifying the original string.Letâs look at a simple example of replace() method.Pythons = "Hello World! Hello Python!" # Replace "Hello" with "Hi" s1 = s.replace("Hello", "Hi") print(
2 min read
Working with Strings in Python 3 In Python, sequences of characters are referred to as Strings. It used in Python to record text information, such as names. Python strings are "immutable" which means they cannot be changed after they are created.Creating a StringStrings can be created using single quotes, double quotes, or even tri
5 min read