Python Program to Converts Characters To Uppercase Around Numbers
Last Updated :
10 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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.
OutputThe 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.
OutputThe 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))
OutputThe 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.
Similar Reads
Python program to uppercase the given characters
Given a string and set of characters, convert all the characters that occurred from character set in string to uppercase() Input : test_str = 'gfg is best for geeks', upper_list = ['g', 'e', 'b'] Output : GfG is BEst for GEEks Explanation : Only selective characters uppercased.Input : test_str = 'gf
7 min read
Python - Test if String contains any Uppercase character
The goal is to check if a given string contains at least one uppercase letter (A-Z). Using any() and isupper()any() function, combined with isdigit(), checks if any character in a string is a digit. It efficiently scans the string and returns True if at least one digit is found.Python# Define the in
3 min read
Python Program To Remove all control characters
In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
3 min read
Python Program for Convert characters of a string to opposite case
Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput: hello every oneOutput: HELLO EVERY ONEExample 1: Python Program for Convert ch
6 min read
Python program to count upper and lower case characters without using inbuilt functions
Given a string that contains both upper and lower case characters in it. The task is to count a number of upper and lower case characters in it. Examples :Input : Introduction to Python Output : Lower Case characters : 18 Upper case characters : 2 Input : Welcome to GeeksforGeeks Output : Lower Case
3 min read
Python Program to convert String to Uppercase under the Given Condition
Given a String list, the task is to write a Python program to convert uppercase strings if the length is greater than K. Examples: Input : test_list = ["Gfg", "is", "best", "for", "geeks"], K = 3 Output : ['Gfg', 'is', 'BEST', 'for', 'GEEKS'] Explanation : Best has 4 chars, hence BEST is uppercased.
5 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 program to find maximum uppercase run
Giving a String, write a Python program to find the maximum run of uppercase characters. Examples: Input : test_str = 'GeEKSForGEEksISBESt' Output : 5 Explanation : ISBES is best run of uppercase. Input : test_str = 'GeEKSForGEEKSISBESt' Output : 10 Explanation : GEEKSISBES is best run of uppercase.
2 min read
Python Program to Generate Random String With Uppercase And Digits
Generating a series of random strings can help create security codes. Besides, there are many other applications for using a random string generator, for instance, obtaining a series of numbers for a lottery game or slot machines. A random string generator generates an alphanumeric string consisting
3 min read
Python - Get the indices of Uppercase characters in given string
Given a String extract indices of uppercase characters. Input : test_str = 'GeeKsFoRGeeks' Output : [0, 3, 5, 7, 8] Explanation : Returns indices of uppercase characters. Input : test_str = 'GFG' Output : [0, 1, 2] Explanation : All are uppercase. Method #1 : Using list comprehension + range() + isu
5 min read