Python – 用 K 替换给定字符串中的所有数字
给定一个包含数字的字符串,将每个数字替换为 K。
Input : test_str = ‘G4G is 4 all No. 1 Geeks’, K = ‘#’
Output : G#G is # all No. # Geeks
Explanation : All numbers replaced by K.
Input : test_str = ‘G4G is 4 all No. Geeks’, K = ‘#’
Output : G#G is # all No. Geeks
Explanation : All numbers replaced by K.
方法 #1:使用 replace() + isdigit()
在此,我们使用 isdigit() 检查数字,replace() 用于执行将数字替换为 K 的任务。
Python3
# Python3 code to demonstrate working of
# Replace numbers by K in String
# Using replace() + isdigit()
# initializing string
test_str = 'G4G is 4 all No. 1 Geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '@'
# loop for all characters
for ele in test_str:
if ele.isdigit():
test_str = test_str.replace(ele, K)
# printing result
print("The resultant string : " + str(test_str))
Python3
# Python3 code to demonstrate working of
# Replace numbers by K in String
# Using regex() + sub()
import re
# initializing string
test_str = 'G4G is 4 all No. 1 Geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '@'
# using regex expression to solve problem
res = re.sub(r'\d', K, test_str)
# printing result
print("The resultant string : " + str(res))
输出
The original string is : G4G is 4 all No. 1 Geeks
The resultant string : G@G is @ all No. @ Geeks
方法 #2:使用 regex() + sub()
在此,适当的正则表达式用于识别数字,而 sub() 用于执行替换。
Python3
# Python3 code to demonstrate working of
# Replace numbers by K in String
# Using regex() + sub()
import re
# initializing string
test_str = 'G4G is 4 all No. 1 Geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '@'
# using regex expression to solve problem
res = re.sub(r'\d', K, test_str)
# printing result
print("The resultant string : " + str(res))
输出
The original string is : G4G is 4 all No. 1 Geeks
The resultant string : G@G is @ all No. @ Geeks