将数字周围的字符转换为大写的Python程序
给定一个字符串,以下程序将任何数字周围的字母字符转换为其大写。
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.
方法一:使用upper() 、 loop和isdigit()
在这里,我们对每个字符进行迭代,检查它是否是数字,如果是,则使用 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))
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))
输出:
The original string is : geeks4geeks is best1 for ge8eks
Transformed String : geekS4Geeks is besT1 for gE8Ek
方法 2:使用列表理解
这与上面的方法类似,唯一的区别是以下在一行中解决了相同的问题。
蟒蛇3
# 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))
输出:
The original string is : geeks4geeks is best1 for ge8eks
Transformed String : geekS4Geeks is besT1 for gE8Ek