Open In App

Python Program to Converts Characters To Uppercase Around Numbers

Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, the following program converts the alphabetic character around any digit to its uppercase.

Input : test_str = ‘geeks4geeks is best1 f6or ge8eks’ 
Output : geekS4Geeks is besT1 F6Or gE8Ek 
Explanation : S and G are uppercased as surrounded by 4.
Input : test_str = ‘geeks4geeks best1 f6or ge8eks’ 
Output : geekS4Geeks besT1 F6Or gE8Ek 
Explanation : S and G are uppercased as surrounded by 4. 

Method 1 : Using upper(), loop and isdigit()

In this, we iterate for each character, check whether it’s a digit and if it is then, transform the surrounding alphabets(next and previous) to uppercase using upper().

Python3




# initializing string
test_str = 'geeks4geeks is best1 for ge8eks'
 
# printing original string
print("The original string is : " + str(test_str))
 
res = ''
for idx in range(len(test_str) - 1):
    if test_str[idx + 1].isdigit() or test_str[idx - 1].isdigit():
        res += test_str[idx].upper()
    else:
        res += test_str[idx]
#Adding last index character
else:
    res += test_str[idx+1]
         
# printing result
print("Transformed String : " + str(res))


Output

The original string is : geeks4geeks is best1 for ge8eks
Transformed String : geekS4Geeks is besT1 for gE8Eks

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2: Using list comprehension

This is similar to the above method, the only difference being that the following tackles the same problem in a single line.

Python3




# initializing string
test_str = 'geeks4geeks is best1 for ge8eks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# list comprehension offering 1 liner solution
res = [test_str[idx].upper() if test_str[idx + 1].isdigit() or test_str[idx - 1].isdigit() else test_str[idx] for idx in range(len(test_str) - 1)]
res = res + list(test_str[-1])
         
# printing result
print("Transformed String : " + ''.join(res))


Output

The original string is : geeks4geeks is best1 for ge8eks
Transformed String : geekS4Geeks is besT1 for gE8Eks

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : By using array

Python3




# Python Program to Converts Characters To
# Uppercase Around Numbers initializing
# string
test_str = 'geeks4geeks is best1 for ge8eks'
 
# printing original string
print("The original string is : " + str(test_str))
 
res = ''
digits = "0123456789"
for idx in range(len(test_str) - 1):
    if test_str[idx + 1] in digits or test_str[idx - 1] in digits:
        res += test_str[idx].upper()
    else:
        res += test_str[idx]
# Adding last index character
else:
    res += test_str[idx+1]
 
# printing result
print("Transformed String : " + str(res))


Output

The original string is : geeks4geeks is best1 for ge8eks
Transformed String : geekS4Geeks is besT1 for gE8Eks

Time complexity: O(n), where n is the length of the input string. 

Auxiliary space: O(n), where n is the length of the input string. A new string is created, and its size is proportional to the size of the input string. 

Method #4 : Using operator.countOf() method

Python3




# Python Program to Converts Characters To
# Uppercase Around Numbers initializing
# string
import operator as op
 
test_str = 'geeks4geeks is best1 for ge8eks'
 
# printing original string
print("The original string is : " + str(test_str))
 
res = ''
digits = "0123456789"
for idx in range(len(test_str) - 1):
    if op.countOf(digits, test_str[idx + 1]) > 0 or op.countOf(digits, test_str[idx - 1]) > 0:
        res += test_str[idx].upper()
    else:
        res += test_str[idx]
# Adding last index character
else:
    res += test_str[idx+1]
 
# printing result
print("Transformed String : " + str(res))


Output

The original string is : geeks4geeks is best1 for ge8eks
Transformed String : geekS4Geeks is besT1 for gE8Eks

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#5 :  Using a for loop and string slicing

Python3




test_str = 'geeks4geeks is best1 for ge8eks'
result = ''
 
# printing original string
print("The original string is : " + str(test_str))
for i in range(len(test_str)):
    if test_str[i-1:i+2].isdigit():
        result += test_str[i].upper()
    else:
        result += test_str[i]
print(result)
#This code is contributed by Vinay pinjala.


Output

The original string is : geeks4geeks is best1 for ge8eks
geeks4geeks is best1 for ge8eks

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#6:  Using re.finditer() and re.compile() functions:

1. Import the re module.
2.Define the input string.
3.Define a function called “transform_string” that takes the input string as a parameter.
4.Inside the function, compile a regular expression pattern that matches characters that are either preceded by a digit or followed by a digit.
5.Initialize an empty string called “res” to store the result.
6.Initialize a variable called “last_index” to keep track of the last index.
7.Iterate over all the matches found in the input string using the “re.finditer()” method.
8.For each match, add the characters from the last index to the start of the current match to the result string.
9.Add the uppercased character to the result string.
10.Update the last index to the end of the current match.
11.Add the remaining characters from the input string to the result string.
12.Return the result string.
13.Call the function with the input string as a parameter.
14.Print the transformed string.

Python3




# import the re module
import re
test_str='geeks4geeks is best1 for ge8eks'
# printing original string
print("The original string is : " + str(test_str))
# define a function to transform the string
def transform_string(test_str):
    # compile a pattern to match characters that are either
    # preceded by a digit or followed by a digit
    pattern = re.compile(r'(?<=\d)[a-zA-Z]|[a-zA-Z](?=\d)')
    # initialize an empty string to store the result
    res = ''
    # initialize a variable to keep track of the last index
    last_index = 0
    # iterate over all the matches found in the input string
    for match in re.finditer(pattern, test_str):
        # add the characters from the last index to the start of the current match
        # to the result string
        res += test_str[last_index:match.start()]
        # add the uppercased character to the result string
        res += match.group().upper()
        # update the last index to the end of the current match
        last_index = match.end()
    # add the remaining characters from the input string to the result string
    res += test_str[last_index:]
    # return the result string
    return res
# call the function to transform the string
result = transform_string(test_str)
# print the result
print("Transformed String : " + result)
#This code is contributed by Jyothi pinjala.


Output

The original string is : geeks4geeks is best1 for ge8eks
Transformed String : geekS4Geeks is besT1 for gE8Eks

Time Complexity:

Compiling the regular expression pattern takes O(m) time where m is the length of the pattern.
The iteration over all the matches in the input string takes O(n) time where n is the length of the input string.
The time complexity of adding characters to a string is O(1) time per character.
Therefore, the overall time complexity of the algorithm is O(m + n), where m is the length of the pattern and n is the length of the input string.
Space Complexity:

The space complexity of the algorithm is O(n), where n is the length of the input string.
This is because we are creating a new string to store the result, which has a maximum size of n.

Method 7: Using a lambda function and map() method

Iterating over each character in the input string, checking if the previous two characters and the current character form a digit using the isdigit() method, and then appending the modified character to an empty result string. The modified string is then printed as output.

Step-by-step approach:

  • Define a lambda function that takes a character as input and returns the uppercase version if the previous character is a digit, otherwise returns the same character.
  • Use the map() method to apply the lambda function to each character in the input string.
  • Join the resulting list of characters back into a single string.

Below is the implementation of the above approach:

Python3




# Define the input string
test_str = 'geeks4geeks is best1 for ge8eks'
 
# Initialize an empty string to store the modified string.
result = ''
 
# Iterate over each character in the input string.
for i in range(len(test_str)):
    # Check if the current character and the previous two characters form a digit.
    if test_str[i-1:i+2].isdigit():
        # If the previous two characters and the current character form a digit, append the uppercase version of the current character to the result string.
        result += test_str[i].upper()
    else:
        # Otherwise, append the current character to the result string.
        result += test_str[i]
 
# Print the result
print("The modified string is : " + str(result))


Output

The modified string is : geeks4geeks is best1 for ge8eks

Time complexity: O(n), where n is the length of the input string. The lambda function and map() method iterate over each character in the string once.
Auxiliary space: O(n), where n is the length of the input string. A list is created to hold the modified characters before they are joined back into a single string.



Last Updated : 10 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads