编写一个从用户那里获取两个字符串的程序。程序应该验证s_short是s_long的子字符串,如果在s_long中找到s_short,程序应该在s_long中打印s_short所在位置的索引位置。如果s_short不是s_long的子字符串,则程序应该打印-1。实施例
RESTART
Enter the long string: aaaaaa
Enter the short string: aa
0 1 2 3
RESTART
Enter the long string: aaaaaaa
Enter the short string: ab
-1
这是我的代码,但它不起作用
s_long=input("Enter a long string:")
s_short=input("Enter a short string:")
for index, s_short in enumerate(s_long):
if (len(s_short))>=0:
print(index)
else:
print("-1")
答案 0 :(得分:1)
你可以这样做:
try:
print s_long.index(s_short)
except ValueError:
print -1
编辑:实际上有一种find方法,与上述所有方法完全相同:
print s_long.find(s_short) # -1 if not found
编辑:如果您需要发生子字符串的所有索引,您可以使用Python的re
模块。