Python - 在第 N 个出现 K字符后提取字符串
给定一个字符串,在第 N 次出现字符后提取字符串。
Input : test_str = ‘geekforgeeks’, K = “e”, N = 2
Output : kforgeeks
Explanation : After 2nd occur. of “e” string is extracted.
Input : test_str = ‘geekforgeeks’, K = “e”, N = 4
Output : ks
Explanation : After 4th occur. of “e” string is extracted.
方法#1:使用split()
这是可以执行此任务的方法之一。在此,我们自定义 split() 以在第 N 个出现时进行拆分,然后使用“-1”打印后提取的字符串。
Python3
# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
# Using split()
# initializing string
test_str = 'geekforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "e"
# initializing N
N = 3
# using split() to perform required string split
# "-1" to extract required part
res = test_str.split(K, N)[-1]
# printing result
print("The extracted string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
# Using re.split()
import re
# initializing string
test_str = 'geekforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "e"
# initializing N
N = 3
# using split() to perform required string split
# "-1" to extract required part
res = re.split(K, test_str, N)[-1]
# printing result
print("The extracted string : " + str(res))
输出
The original string is : geekforgeeks
The extracted string : eks
方法 #2:使用 re.split()
这是解决这个问题的另一种方法。与上面的函数类似,我们执行 split() 来执行拆分任务,但来自正则表达式库,它也提供了在第 N 次出现时拆分的灵活性。
蟒蛇3
# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
# Using re.split()
import re
# initializing string
test_str = 'geekforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "e"
# initializing N
N = 3
# using split() to perform required string split
# "-1" to extract required part
res = re.split(K, test_str, N)[-1]
# printing result
print("The extracted string : " + str(res))
输出
The original string is : geekforgeeks
The extracted string : eks