2013-03-13 64 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模塊。

相關問題