Python – 测试子字符串是否出现在特定位置
有时,在使用Python字符串时,我们可能会遇到需要测试子字符串出现的问题。有直接的方法来测试这个。但有时,我们有一个更具体的问题,我们需要测试子字符串是否出现在该特定位置。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是解决这个问题的蛮力方法。在此我们迭代字符串,当索引出现时,我们同时测试子字符串字符。
# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using loop
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using loop
res = True
k = 0
for idx in range(len(test_str)):
if idx >= i and idx < j:
if test_str[idx] != substr[k]:
res = False
break
k = k + 1
# printing result
print("Does string contain substring at required position ? : " + str(res))
输出 :
The original string is : Gfg is best
Does string contain substring at required position ? : True
方法#2:使用字符串切片
这是执行此任务的单线方式。在此,我们使用字符串切片检查字符串中的子字符串。
# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using string slicing
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using string slicing
res = test_str[i : j] == substr
# printing result
print("Does string contain substring at required position ? : " + str(res))
输出 :
The original string is : Gfg is best
Does string contain substring at required position ? : True