Python - Uppercase Selective Substrings in String
Last Updated :
25 Apr, 2023
Given a String, perform uppercase of particular Substrings from List.
Input : test_str = 'geeksforgeeks is best for cs', sub_list = ["best", "geeksforgeeks"]
Output : GEEKSFORGEEKS is BEST for cs
Explanation : geeksforgeeks and best uppercased.
Input : test_str = 'geeksforgeeks is best for best', sub_list = ["best", "geeksforgeeks"]
Output : GEEKSFORGEEKS is BEST for BEST
Explanation : geeksforgeeks and best both occurrences uppercased.
Method #1 : Using split() + join() + loop
In this, we repeatedly split the string by substring and then perform join operation after joining the String with uppercased version of Substring. This is a success only in cases of 1 occurrence of a substring in a string.
Python3
# Python3 code to demonstrate working of
# Uppercase Selective Substrings in String
# Using split() + join() + loop
# initializing strings
test_str = 'geeksforgeeks is best for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing substrings
sub_list = ["best", "cs", "geeksforgeeks"]
for sub in sub_list:
# splitting string
temp = test_str.split(sub, -1)
# joining after uppercase
test_str = sub.upper().join(temp)
# printing result
print("The String after uppercasing : " + str(test_str))
OutputThe original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS
Method #2 : Using re.sub() + upper()
This uses regex to solve this problem. In this, we use appropriate regex and perform uppercase of found Strings.
Python3
# Python3 code to demonstrate working of
# Uppercase Selective Substrings in String
# Using re.sub() + upper()
import re
# initializing strings
test_str = 'geeksforgeeks is best for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing substrings
sub_list = ["best", "cs", "geeksforgeeks"]
# constructing regex
reg = '|'.join(sub_list)
res = re.sub(reg, lambda ele: ele.group(0).upper(), test_str)
# printing result
print("The String after uppercasing : " + str(res))
OutputThe original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using replace() and upper() methods
Python3
# Python3 code to demonstrate working of
# Uppercase Selective Substrings in String
# initializing strings
test_str = 'geeksforgeeks is best for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing substrings
sub_list = ["best", "cs", "geeksforgeeks"]
for sub in sub_list:
test_str = test_str.replace(sub, sub.upper())
# printing result
print("The String after uppercasing : " + str(test_str))
OutputThe original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS
Method #4:Using NumPy
Algorithm:
- Initialize an empty list res.
- Loop through each element 'ele' in the set of Kth indices obtained from the input list.
- Find the first tuple in the input list where the Kth index matches ele, using the next() function and a generator expression.
- Append the found tuple to the res list.
- Return the res list.
Python3
import numpy as np
# initializing string and substrings
test_str = 'geeksforgeeks is best for cs'
sub_list = ["best", "cs", "geeksforgeeks"]
# splitting string into words
words = np.array(test_str.split())
# initializing boolean array to keep track of which words need to be capitalized
to_upper = np.zeros_like(words, dtype=bool)
# marking words that match any of the substrings
for sub in sub_list:
to_upper[words == sub] = True
# capitalizing selected words
words[to_upper] = np.char.upper(words[to_upper])
# joining words back into a string
result_str = ' '.join(words)
# printing result
print("The String after uppercasing : " + str(result_str))
Output
The String after uppercasing : GEEKSFORGEEKS is BEST for CS
Time Complexity: O(n^2), where n is the number of tuples in the input list. This is because the algorithm involves nested loops to iterate over the tuples and set of Kth indices.
Auxiliary Space: O(n), where n is the number of tuples in the input list. This is because we need to store the resulting tuples in the res list.
Method#5: Using Recursive method
Sure, here's the algorithm for the uppercase_selective_substrings function:
- Check if the sub_list is empty. If it is, return the test_str.
- Set sub as the first substring in the sub_list.
- Find all occurrences of sub in test_str using the startswith method.
- For each occurrence of sub, create a new string by replacing sub with its uppercase version in test_str.
- Call the uppercase_selective_substrings function recursively with the new string and the remaining substrings in the sub_list.
- Return the final result string.
Example:
Python3
def uppercase_selective_substrings(test_str, sub_list):
if not sub_list:
return test_str
sub = sub_list[0]
# find all occurrences of substring
indices = [i for i in range(len(test_str)) if test_str.startswith(sub, i)]
# uppercase each occurrence of substring
for index in indices:
new_str = test_str[:index] + sub.upper() + test_str[index+len(sub):]
test_str = uppercase_selective_substrings(new_str, sub_list[1:])
return test_str
test_str = 'geeksforgeeks is best for cs'
sub_list = ["best", "cs", "geeksforgeeks"]
result_str = uppercase_selective_substrings(test_str, sub_list)
print("The String after uppercasing : " + str(result_str))
OutputThe String after uppercasing : GEEKSFORGEEKS is BEST for CS
Time complexity: O(nm), where n is the length of the input string and m is the total number of occurrences of all the substrings in the input string. This is because the algorithm needs to iterate over the entire input string to find all the occurrences of each substring.
Auxiliary space: O(nm), because at each recursive call, a new string is created with an uppercase substring, which may have a maximum length of n. The number of recursive calls is also proportional to the number of occurrences of all the substrings in the input string, which is bounded by m.
Method 6: Using loop
Here we will be iterating through each substring in the list and then using the built-in string methods index() and slice notation.
Approach:
- Define a function called uppercase_selective_substrings that takes two parameters: test_str, which is the input string, and sub_list, which is a list of substrings that need to be uppercased in the input string.
- Inside the function, loop through each substring in sub_list using a for loop.
- Initialize a variable i to 0, which will be used to keep track of the starting index of each occurrence of the current substring in the input string.
- Start a while loop that will continue until all occurrences of the current substring have been uppercased. Inside the loop, use the find() method to find the next occurrence of the current substring in the input string, starting from index i. If find() returns -1, it means there are no more occurrences of the substring, so break out of the loop.
- Use string slicing and concatenation to replace the current occurrence of the substring in the input string with its uppercase version. The substring to be uppercased is test_str[i:i+len(sub)], so concatenate test_str[:i] (the part of the string before the current occurrence), sub.upper() (the uppercase version of the current substring), and test_str[i+len(sub):] (the part of the string after the current occurrence) to create the new version of the string.
- Update i to the index of the character immediately following the end of the current occurrence of the substring, so that the next iteration of the loop will start searching for the next occurrence of the substring at the correct index.
- Return the modified input string.
- Create a variable test_str and set it to the input string "geeksforgeeks is best for cs".
- Create a variable sub_list and set it to a list containing the substrings "best", "cs", and "geeksforgeeks".
- Call the uppercase_selective_substrings() function with test_str and sub_list as arguments, and assign the result to a variable called result_str.
- Print out the result string with a message to indicate that it is the string after uppercasing.
- The output of the program should be "The String after uppercasing: GEEKSFORGEEKS is BEST for CS".
Example:
Python3
def uppercase_selective_substrings(test_str, sub_list):
for sub in sub_list:
i = 0
while True:
i = test_str.find(sub, i)
if i == -1:
break
test_str = test_str[:i] + sub.upper() + test_str[i+len(sub):]
i += len(sub)
return test_str
# input string and list
test_str = 'geeksforgeeks is best for cs'
sub_list = ["best", "cs", "geeksforgeeks"]
result_str = uppercase_selective_substrings(test_str, sub_list)
# Printing list
print("The String after uppercasing : " + str(result_str))
OutputThe String after uppercasing : GEEKSFORGEEKS is BEST for CS
Time complexity: O(N*M), where n is the length of the input string and m is the total length of all substrings in the list.
Auxiliary space: O(1)
Similar Reads
Python - Random uppercase in Strings
Given a String, the task is to write a Python program to convert its characters to uppercase randomly. Examples: Input : test_str = 'geeksforgeeks' Output : GeeksfORgeeks Explanation : Random elements are converted to Upper case characters. Input : test_str = 'gfg' Output : GFg Explanation : Random
4 min read
Python - Selectively Split in Strings
Sometimes, while working with Python strings, we may have to perform a split. Not sometimes, normal one, depending on deliminator but something depending upon programming constructs like elements, numbers, words etc and segregate them. Lets discuss a way in which this task can be solved. Method : Us
3 min read
Python - Remove after substring in String
Removing everything after a specific substring in a string involves locating the substring and then extracting only the part of the string that precedes it. For example we are given a string s="Hello, this is a sample string" we need to remove the part of string after a particular substring includin
3 min read
Python program to Uppercase selective indices
Given a String perform uppercase to particular indices. Input : test_str = 'geeksgeeksisbestforgeeks', idx_list = [5, 7, 3, 2, 6, 9] Output : geEKsGEEkSisbestforgeeks Explanation : Particular indices are uppercased. Input : test_str = 'geeksgeeksisbestforgeeks', idx_list = [5, 7, 3] Output : geeKsGe
7 min read
Python - Remove substring list from String
Our task is to remove multiple substrings from a string in Python using various methods like string replace in a loop, regular expressions, list comprehensions, functools.reduce, and custom loops. For example, given the string "Hello world!" and substrings ["Hello", "ld"], we want to get " wor!" by
3 min read
Python | Remove the given substring from end of string
Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Â Â Remove the substring from the end of the string using Slicing In
3 min read
Python - Uppercase Half String
The problem is to convert half of a string to uppercase, either the first half or the second half, depending on the requirement. For example, given the string "python", the output could be "PYThon" (uppercase first half) or "pytHON" (uppercase second half).If the string length is odd, handle the mid
2 min read
Python - String till Substring
When working with Python strings, we may encounter a situation where we need to extract a portion of a string that starts from the beginning and stops just before a specific substring. Let's discuss certain ways in which we can do this.Using split()The split() method is a simple and efficient way to
3 min read
Ways to split strings on Uppercase characters - Python
Splitting strings on uppercase characters means dividing a string into parts whenever an uppercase letter is encountered.For example, given a string like "CamelCaseString", we may want to split it into ["Camel", "Case", "String"]. Let's discuss different ways to achieve this.Using Regular Expression
3 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Letâs try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the in
4 min read