2014-01-15 66 views
0

我試圖檢查一個單詞是否有尾隨分號。我有一個長字符串中的單詞的位置,我想檢查位置start of word + length of word上的字符是否爲:。它可以是單詞是字符串中的最後一個字,因此試圖讓下一個字符將引發IndexException使用assert控制流程

我有三個想法:

1)檢查,我們是沒底的字符串,然後檢查其沒有分號

semicolon_pos = pos_word + len(word) # Possible position 
if semicolon_pos < len(long_string) and long_string[semicolon_pos] == ':': 
    # do something... 
else: 
    # do something else 

不是它通常被認爲是Python的

2)嘗試 - 除了分號前牽引和分號

semicolon_pos = pos_word + len(word) # Possible position 
try: 
    if long_string[semicolon_pos] == ':': 
     # Do something 
    else: 
     # do something else (which is the same as in the except clause) 

except IndexError: 
    # do something else 

平等看起來有點有點不可思議,提取,然後嵌套。我必須做一個小動作,以避免重複代碼

3)嘗試 - 除了分號提取和斷言,以確保它是一個分號

semicolon_pos = pos_word + len(word) # Possible position 
try: 
    assert long_string[semicolon_pos] == ':' 
    # do something 
except (IndexError, AssertionError): 
    # do something else 

結構扁平化,這是容易閱讀,但我有一種濫用異常使用的感覺。

python的人說什麼? 在此先感謝。

+0

我想我覆蓋了一條評論。我也在編輯自己。抱歉! – bgusach

+2

endswith(':')? – daveoncode

+0

對我來說看起來相當pythonic。您可以考慮在代碼審查中詢問這一點。重要的是要清楚你的意圖是什麼,所以你可能想把它包裝在一個函數'colon_follows_word'中。 –

回答

1

最簡單的方法就是使用切片作爲下標。切片不扔IndexError:

semicolon_pos = pos_word + len(word) # Possible position 
if long_string[semicolon_pos:semicolon_pos+1] == ':': 
    # Do something 
else: 
    # do something else 
+0

既然你先給了這個想法,我會把它標記爲正確的。它的時間和時間比檢查長度然後比較更有效。謝謝。 – bgusach

2

(string[index] if index < len(string) else None) == ':'

+0

這比分片效率低 – bgusach

1

我覺得它更容易這樣:

#considering mylongstring contains the word 
#+1 for the possible colon 
mylongstring[:pos_word + len(word) + 1].endswith(':') 

或者,如果長字符串是很長的,你不想複製太多:

mylongstring[pos_word:pos_word + len(word) + 1][-1] == ':' 
+0

我不知道多久'mylongstring'是,但是如果它真的很長,那麼爲了檢查最後一個字符可能需要很長的時間。提取你想測試的一個字符可能會更好。 – Duncan

+0

它的平均情況並不是很長,但我希望和possbiel一樣高效。該字符和下一個字符之間的切片對我來說看起來相當不錯。我會直接比較':'而不是'endswith'。 – bgusach

+0

@ ikaros45:的確: 在[1]:timeit -n 100000 a.endswith( 「:」) 100000循環,最好的3:每次循環 159納秒在[2]:timeit -n 100000 [ -1] ==「:」 100000循環,最好是3:每循環78.6 ns – ProfHase85

3

絕對是錯誤的斷言。原因:當代碼與-O標誌一起運行時,甚至不會執行斷言。

建議使用斷言的方法是檢查算法中的錯誤(後置條件)導致的「不可能」條件。對於前提條件和程序邏輯,應該使用普通的例外。

+0

可能是我在這裏學到的最有趣的東西,雖然只是部分答案。謝謝。 – bgusach