Python|在给定子字符串出现后获取字符串
有时,除了查找子字符串之外,我们可能还需要获取在找到子字符串之后出现的字符串。让我们讨论可以执行此任务的某些方式。
方法 #1:使用partition()
分区函数可用于执行此任务,其中我们只返回分区词之后出现的分区部分。
# Python3 code to demonstrate
# Get String after substring occurrence
# using partition()
# initializing string
test_string = "GeeksforGeeks is best for geeks"
# initializing split word
spl_word = 'best'
# printing original string
print("The original string : " + str(test_string))
# printing split string
print("The split string : " + str(spl_word))
# using partition()
# Get String after substring occurrence
res = test_string.partition(spl_word)[2]
# print result
print("String after the substring occurrence : " + res)
输出 :
The original string : GeeksforGeeks is best for geeks
The split string : best
String after the substring occurrence : for geeks
方法 #2:使用split()
split函数也可以用来执行这个特定的任务,在这个函数中,我们使用限制 split 的力量,然后打印后面的字符串。
# Python3 code to demonstrate
# Get String after substring occurrence
# using split()
# initializing string
test_string = "GeeksforGeeks is best for geeks"
# initializing split word
spl_word = 'best'
# printing original string
print("The original string : " + str(test_string))
# printing split string
print("The split string : " + str(spl_word))
# using split()
# Get String after substring occurrence
res = test_string.partition(spl_word)[2]
# print result
print("String after the substring occurrence : " + res)
输出 :
The original string : GeeksforGeeks is best for geeks
The split string : best
String after the substring occurrence : for geeks