Skip to content
Related Articles

Related Articles

Python Program to Converts Characters To Uppercase Around Numbers

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 12 Aug, 2022
View Discussion
Improve Article
Save Article

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 gE8Ek

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 gE8Ek

Time Complexity: O(n)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!