2016-07-28 12 views
0

私はstring.replace forループを使用したいと思います。これは私のコードです:Python forループでString.Replaceを使用してください。

new = ['p','q','r'] 
my_str = 'there are two much person a, person b, person c.' 
old = ['a','b','c'] 

for i in range(0,len(old)): 
    my_str = string.replace(my_str,old[i],new[i]) 

print(my_str) 

しかし、私にエラー与えている:

TypeError: 'str' object cannot be interpreted as an integer

所望の出力:これは単なる一例である

there are two much person p, person q, person r.

を、私はのためのforループを実行したいです10,000の長さのリスト。

+2

there are two much person p, person q, person r.を再現することはできません。あなたのコードはPython 2.7でうまく動作します –

+0

'string.replace'関数は非常に長い間廃止されました。代わりに'str.replace'メソッドを使うべきです。 –

+4

あなたが知っている奇妙な問題を修正しても、あなたはまだ 'are 'の' a'と 'much'の' c'を置き換えるつもりです。 – user2357112

答えて

2

new = ['p','q','r'] 
my_str = 'there are two much person a, person b, person c.' 
old = ['a','b','c'] 

for i in range(len(old)): 
    my_str = my_str.replace(old[i],new[i]) 

print(my_str) 

を試してみたが、古いのエントリは、あなたがこれもあれば、二重の交換問題を回避

import re 

new = ['p','q','r'] 
my_str = 'there are two much person a, person b, person c.' 
old = ['a','b','c'] 

word=re.compile(r"\w*") # word characters 
old_new=dict(zip(old,new)) 
ong=old_new.get 
my_str=word.sub((lambda s:ong(s,s)),my_str) 

print(my_str) 

を行うことができ、すべての文字のみであれば、それはpropably

非常に高速ではありませんエントリは古いものと新しいものの両方にあります(短いソリューションでは避けられません)

1

string.replace()はPython 2.xでは使用できますが、Python 3.xでは非推奨です。以下は

は、あなたがあなたのケースではPython 3.xの

str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

でそれを使用する方法である、それは私があなたの問題を再現することはできません、my_str.replace(old[index], new[index])

2

実際にあります。あなたのコードはPython 2.7上で正常に動作します。しかし、それを行うより良い方法があります。しかし、これはまだareaを交換し、muchc、それはまたで導入された文字を置き換える可能性があるだろう

for i in range(0,len(old)): 
    my_str = string.replace(my_str,old[i],new[i]) 

:まず、代わりにrangeを使用して、あなたはoldnewリストをzipことができこれはおそらくあなたが望むものではありません。代わりに、reモジュールを使用して、置換する文字列を|に正規表現に結合し、それを\bの単語境界文字で区切ります。あなたの場合は\b(a|b|c)\bとし、辞書を使用して適切な置換えを検索してください。

d = dict(zip(old, new)) 
p = r'\b(' + '|'.join(old) + r')\b' 
my_str = re.sub(p, lambda m: d.get(m.group()), my_str) 

結果:

+0

私の解決策のようなものですが、これはoldのエントリが単語文字 – janbrohl

+0

'.join(old)'のみが 'len(old)'が10000ならば良いとは限りません。 ... –

+0

@ PM2Ring良い点、この光の中では、ジャンブロフのソリューションがうまくいくかもしれません。 +1 –

関連する問題