2011-11-17 183 views
5

的第三次出現後,我想第三個字符之後剝離所有的字符,比如 - 例如。地帶串字符蟒蛇

我發現這個代碼在網上和它的作品,但我有麻煩學習它是如何工作的,並要問,所以我可以完全理解。

def indexList(s, item, i=0): 
    """ 
    Return an index list of all occurrances of 'item' in string/list 's'. 
    Optional start search position 'i' 
    """ 
    i_list = [] 
    while True: 
     try: 
      i = s.index(item, i) 
      i_list.append(i) 
      i += 1 
     except: 
      break 
    return i_list 

def strip_chrs(s, subs): 
    for i in range(indexList(s, subs)[-1], len(s)): 
     if s[i+1].isalpha(): 
      return data[:i+1] 

data = '115Z2113-3-777-55789ABC7777' 
print strip_chrs(data, '-') 

這裏是我的問題 上,而真:線什麼是真的嗎? 另外除了:除了什麼?爲什麼會在那裏編碼?

在此先感謝!

+0

爲什麼你標記這個Python 3.x?您在'print'語句中使用Python 2.x語法。 –

+0

你是否想在第三次出現另一個人之後去除所有人物?因此,在你的'data'例子中,你是否試圖在'115Z2113-3-777'之後去掉所有的東西? – Casey

+0

是的,55789ABC7777應該被剝離。我標記了Python 3.x,因爲我目前正在學習它。我會刪除標籤,儘管我很抱歉 – canyon289

回答

22

這裏有一個辦法:

def trunc_at(s, d, n=3): 
    "Returns s truncated at the n'th (3rd by default) occurrence of the delimiter, d." 
    return d.join(s.split(d, n)[:n]) 

print trunc_at("115Z2113-3-777-55789ABC7777", "-") 

它是如何工作的:

  1. 字符串s被分成每一個列表使用s.split(d)時出現分隔符d。我們使用的第二個參數split指示分裂的最大數量做(因爲沒有理由繼續分裂第一n次後)。其結果是一個列表,如["115Z2113", "3", "777", "55789ABC7777"]
  2. 第一n項列表的的切片使用[:n]服用。其結果是另一個列表,如["115Z2113", "3", "777"]
  3. 清單加入回字符串,將分隔符d列表中的每個項目之間,使用d.join(...),導致,例如,"115Z2113-3-777"
+0

我喜歡。 愚蠢的長度限制。 –

+0

爲簡單起見,+1爲不使用itertools :) –

4

while True: 

創建無限循環。它會一直循環,直到程序崩潰或調用breakexcept行是一個異常處理程序,它將捕獲任何異常,此時break被稱爲退出無限循環。

1

在 「真時」,真正是簡單常數值true。所以雖然True是永久循環或直到破碎。

的,除了使用異常時s.index後,我發現沒有更多的字符串,以此來打破循環出現這種情況。這是一件壞事。

嘗試這樣的事情(僞):

while you still have string left: 
    get index of next '-' 
    if found, add 1 to count 
    if count == 3: 
     return s[index+1:] 

s[index+1:]收益從以下索引字符的字符串,到最後。

7

在一個班輪方式:

data = '115Z2113-3-777-55789ABC7777' 
strip_character = "-" 
>>> strip_character.join(data.split(strip_character)[:3]) 
'115Z2113-3-777'