2017-06-10 2 views
0

私は.split()文字列メソッドを複製しようとしています。それはうまくいくが、最後の言葉は含まれていない。split()文字列メソッドを使用しないsplit関数の使用。ほとんど

def stringSplitter(string): 
    words = [] 
    current_word = "" 
    for x in range(len(string)): #problem is here 
     if string[x] == " ": 
      words.append(current_word) 
      current_word = "" 
     else: 
      current_word += string[x] 
    return words 

テスト1:文=私は私の自転車に乗るのが好き場合は、自分のコードが正しく出力:

['I', 'like', 'to', 'ride', 'my'] 

私が望む結果は次のとおりです。

['I', 'like', 'to', 'ride', 'my', 'bicycle'] 
+0

Python for Loopでインデックスを使用している場合は、通常何か問題があります。 – Rosh

答えて

3

だけ返す前words.append(current_word)を追加します。関数から。それがあなたの「失われた」言葉です。また、rangeまたはインデックス作成のいずれかを使用する必要はありません。 for x in string:は文字の直ぐ上を繰り返します。

+0

ありがとうございます!最後に、これが私の欠けているものです。 – lloydyu24

0

@DYZの最初の回答の助けを借りて得ました。ありがとうございました!どうやら、私は最後の言葉をスキップしていました。なぜなら、復帰の前に(以下)を追加する必要があるからです。

words.append(current_word) 

マイコード:これはジェネレータ関数を使用して、より簡潔に実装することができ

def stringSplitter(string): 
    words = [] 
    current_word = "" 
    for char in string: 
     if char == " ": 
      words.append(current_word) 
      current_word = "" 
     else: 
      current_word += char 
    words.append(current_word)   
    return words 
1

注 - あなたは「本当の」str.split()機能の実装から少し逸脱気にしなかった場合:

>>> def split(string, delimiter=' '): 
    current_word = '' 
    for char in string: 
     if char == delimiter: 
      yield current_word 
      current_word = '' 
     else: 
      current_word += char 
    yield current_word 


>>> list(split('I like to ride my bicycle')) 
['I', 'like', 'to', 'ride', 'my', 'bicycle'] 
>>> 

あなたも同様に区切り文字を返すできるようにそれを修正することができます:

>>> def split(string, delimiter=' ', save_delimiter=False): 
    current_word = '' 
    for char in string: 
     if char == delimiter: 
      yield current_word 
      if save_delimiter: 
       yield char 
      current_word = '' 
     else: 
      current_word += char 
    yield current_word 


>>> list(split('I like to ride my bicycle', save_delimiter=True)) 
['I', ' ', 'like', ' ', 'to', ' ', 'ride', ' ', 'my', ' ', 'bicycle'] 
>>> 
関連する問題