Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program To Remove all control characters
Next article icon

Python Program to Converts Characters To Uppercase Around Numbers

Last Updated : 10 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.



Next Article
Python Program To Remove all control characters
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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. [GFGTABS] Python # D
    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
    7 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences