2013-03-13 65 views
-1

编写一个程序,用户需要两个字符串。程序应该验证s_short是s_long的一个子字符串,如果s_short在s_long中被发现,程序应该在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") 
+3

欢迎来到Stack Overflow!看起来你希望我们为你写一些代码。尽管许多用户愿意为遇险的编码人员编写代码,但他们通常只在海报已尝试自行解决问题时才提供帮助。证明这一努力的一个好方法是包含迄今为止编写的代码,示例输入(如果有的话),期望的输出和实际获得的输出(控制台输出,堆栈跟踪,编译器错误 - 无论是适用)。您提供的细节越多,您可能会收到的答案就越多。 – 2013-03-13 21:52:35

+0

查看're'模块或使用条件'in'来测试短字符串是否在长字符串中 – PurityLake 2013-03-13 21:54:48

+0

请访问www.whathaveyoutried.com – 2013-03-13 21:55:09

回答

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模块。

相关问题