2016-10-23 136 views
0

我有下一個問題。代碼完美地抓住了標籤,但是......我怎麼能把第二個「同時」的通道完成?IndexError:字符串索引超出範圍:多一次

如果我把這個道:

hash = '#hhhh #asdasd' 

代碼不需額外編譯。我該如何改變這一段?預先感謝。 例外:

while hash[indexA + 1] not in {' ', '#'}: 
IndexError: string index out of range 

下面是代碼:

hash = '#hhhh #asdasd ' 
indexA = 0 
copy = '' 
indexB = indexA 

while indexA < len(hash): 
    indexB = indexA 
    copy = '' 

    if hash[indexA] == '#' and indexA + 1 < len(hash): 
     while hash[indexA + 1] not in {' ', '#'}: 
      indexA += 1 
      copy = hash[indexB:indexA + 1] 

     if len(copy) > 1: 
      print('newHashtag: ' + copy) 

     if hash[indexA + 1] == ' ': 
      indexA += 1 

    else: 
     indexA += 1 
+2

'while indexA Li357

+1

此代碼在我的Python解釋器中工作。順便說一句,'hash'是Python中的一個內置函數,覆蓋它不是一個好主意。 – pivanchy

+0

如果我明白你在做什麼,你應該真正使用這個正則表達式。如果你的字符串永遠是正常的,你甚至可以使用'split'。 –

回答

1

,因爲您沒有檢查散列的長度你有指標的問題。這應該工作:

hash = '#hhhh #asdasd' 
indexA = 0 
copy = '' 
indexB = indexA 

while indexA < len(hash): 
    indexB = indexA 
    copy = '' 

    if hash[indexA] == '#' and indexA + 1 < len(hash): 
     while indexA + 1 < len(hash) and hash[indexA + 1] not in {' ', '#'}: 
      indexA += 1 
      copy = hash[indexB:indexA + 1] 

     if len(copy) > 1: 
      print('newHashtag: ' + copy) 

     if indexA + 1 < len(hash) and hash[indexA + 1] == ' ': 
      indexA += 1 

    else: 
     indexA += 1 
2

如果你想找到字符串變量,你可以做到這一點很容易,用多Python的方式:

some_string = "#tag1 #tag2 something else #tag3" 
tags = [tag.strip("#") for tag in some_string.split() if tag.startswith("#")] 

>>> print tags 
['tag1', 'tag2', 'tag3'] 

在標籤的情況下,沒有空格,你可以寫的東西像這樣:

some_string = "#tag1 #tag2 something else #tag3 #moretags#andmore" 
tags = [] 
for tag in some_string.split(): 
    if '#' in tag: 
     multi_tags = tag.split('#') 
     tags.extend([t for t in multi_tags if t]) 

>>> tags 
['tag1', 'tag2', 'tag3', 'moretags', 'andmore'] 
+0

根據OP代碼,標籤之間可能沒有空格,因此您的解決方案可能無法正常工作。 – acw1668

+0

我想學習像你這樣的編程 –

+0

@Danicroquebelmar,經過多年使用Python的經驗,你會像我一樣編程:)但是嘗試使用Python功能來解決你的任務,但不要使用Python編寫類似Basic的代碼:) – pivanchy

相關問題