Open In App

Python – Uppercase Selective Substrings in String

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Output

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


Output

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


Output

The original string is : geeksforgeeks is best for cs
The String after uppercasing : GEEKSFORGEEKS is BEST for CS

Method #4:Using NumPy

Algorithm:

  1. Initialize an empty list res.
  2. Loop through each element ‘ele’ in the set of Kth indices obtained from the input list.
  3. Find the first tuple in the input list where the Kth index matches ele, using the next() function and a generator expression.
  4. Append the found tuple to the res list.
  5. 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:

  1. Check if the sub_list is empty. If it is, return the test_str.
  2. Set sub as the first substring in the sub_list.
  3. Find all occurrences of sub in test_str using the startswith method.
  4. For each occurrence of sub, create a new string by replacing sub with its uppercase version in test_str.
  5. Call the uppercase_selective_substrings function recursively with the new string and the remaining substrings in the sub_list.
  6. 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))


Output

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

  1. 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.
  2. Inside the function, loop through each substring in sub_list using a for loop.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. Return the modified input string.
  8. Create a variable test_str and set it to the input string “geeksforgeeks is best for cs”.
  9. Create a variable sub_list and set it to a list containing the substrings “best”, “cs”, and “geeksforgeeks”.
  10. Call the uppercase_selective_substrings() function with test_str and sub_list as arguments, and assign the result to a variable called result_str.
  11. Print out the result string with a message to indicate that it is the string after uppercasing.
  12. 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))


Output

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads