Python – 删除 K 后的 N 个字符
给定一个字符串,删除 K 个字符后的 N 个字符。
Input : test_str = ‘ge@987eksfor@123geeks is best@212 for cs’, N = 3, K = ‘@’
Output : ‘geeksforgeeks is best for cs’
Explanation : All 3 required occurrences removed.
Input : test_str = ‘geeksfor@123geeks is best for cs’, N = 3, K = ‘@’
Output : ‘geeksforgeeks is best for cs’
Explanation : @123 is removed.
方法#1:使用 re.sub()
在此,我们指定适当的正则表达式来捕获元素并从字符串中删除接下来的 N 次出现。 sub() 用于执行替换。
Python3
# Python3 code to demonstrate working of
# Remove N characters after K
# Using re.sub()
import re
# initializing strings
test_str = 'geeksfor@123geeks is best@212 for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing N
N = 3
# initializing K
K = '@'
# using re.sub() to perform task
res = re.sub(r'\@...', '', test_str)
# printing result
print("The String after removal : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove N characters after K
# Using re.sub() + occurrence option
import re
# initializing strings
test_str = 'geeksfor@123geeks is best@212 for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing N
N = 3
# initializing K
K = '@'
# using re.sub() to perform task
# controlling occurrence using 4th arg.
# removes just 1st occurrence
res = re.sub(r'\@...', '', test_str, 1)
# printing result
print("The String after removal : " + str(res))
输出
The original string is : geeksfor@123geeks is best@212 for cs
The String after removal : geeksforgeeks is best for cs
方法#2:使用 re.sub() + 出现选项
这与上面类似,只是使用 re.sub() 的第四个参数来控制我们希望执行替换的出现次数。
Python3
# Python3 code to demonstrate working of
# Remove N characters after K
# Using re.sub() + occurrence option
import re
# initializing strings
test_str = 'geeksfor@123geeks is best@212 for cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing N
N = 3
# initializing K
K = '@'
# using re.sub() to perform task
# controlling occurrence using 4th arg.
# removes just 1st occurrence
res = re.sub(r'\@...', '', test_str, 1)
# printing result
print("The String after removal : " + str(res))
输出
The original string is : geeksfor@123geeks is best@212 for cs
The String after removal : geeksforgeeks is best@212 for cs