2016-12-11 6 views
0

を置き換える:次の行に移動し、私は例えば、文字列を持っている

私はリストから別の単語と「文」を置き換えたい
String = "This is first sentence, sentence one. This is second sentence, sentence two`." 

はそう

my_list = ['1', 'me1', '2', 'me2'] 

ことになるだろう:

"This is first 1, me1 one. This is second 2, me2 two." 

+0

SOはチュートリアルサービスではありません。 *あなたは何を試しましたか*、それに正確に何が問題ですか? – jonrsharpe

+0

'str.replace'は3番目のオプションの' count'引数をとります。これを1に設定すると、一度に1つずつオカレンスを置き換えることができます。また、 'String'中の' sentence'の出現回数が 'my_list'の長さと等しくない場合はどうでしょうか? –

答えて

0
String = "This is first sentence, sentence one. This is second sentence, sentence two`." 
String1 = String 
my_list = ['1', 'me1', '2', 'me2'] 

for i in range(len(my_list)): 
    String1=String1.replace("sentence",my_list[i],1) 
    print i, my_list[i] 
print String1 

アウトは入れ:

'This is first 1, me1 one. This is second 2, me2 two`.' 
1

置換コールバックとしてregex.sub(repl, string, count=0)機能やカスタムreplace_substring機能を使用してソリューション:

def replace_substring(m): 
    if replace_substring.counter == len(my_list): 
     replace_substring.counter = 0 

    replaced = my_list[replace_substring.counter] 
    replace_substring.counter += 1 
    return replaced 

replace_substring.counter = 0 

String = "This is first sentence, sentence one. This is second sentence, sentence two`." 
my_list = ['1', 'me1', '2', 'me2'] 
pattern = re.compile(r'\bsentence\b') 

result = pattern.sub(replace_substring, String) 
print(result) 

出力:

This is first 1, me1 one. This is second 2, me2 two`. 

https://docs.python.org/3/library/re.html#re.regex.sub

関連する問題