python字符串替换函数参数

时间:2015-03-03 08:11:51

标签: python

str1 = ["is" , "first"]       
str2 = ["was" , "second"]          
str3 = "he is doing his first year graduation"       
for i in RANGE(len(str1)):      
str4 = str3.replace(str1[i],str2[i])    

由于不可变属性只有第二个更改(“first”到“second”)。我怎样才能将两个变化结合在一起。实际上我有一个巨大的字符串大小。我是python的新手,请帮帮我

4 个答案:

答案 0 :(得分:3)

只需将最后一行指定给str3

str1 = ["is" , "first"]       
str2 = ["was" , "second"]          
str3 = "he is doing his first year graduation"       
for i in range(len(str1)):      
    str3 = str3.replace(str1[i],str2[i])  

print str3  # he was doing hwas second year graduation

注意 中的单词"他的"也正在被取代!

如果你想要一个"确切的"匹配,使用正则表达式模块:

import re

str1 = ["is" , "first"]       
str2 = ["was" , "second"]          
str3 = "he is doing his first year graduation"       
for i in range(len(str1)):      
    str3 = re.sub(r'\b{}\b'.format(str1[i]),str2[i], str3)  

print str3  # he was doing his second year graduation

答案 1 :(得分:1)

您可以通过应用reducelambda

在一行中完成

ans = reduce(lambda n, (old, new): n.replace(old, new), zip(str1,str2), str3)

示例:

>>> str1 = ["is", "first"]
>>> str2 = ["was", "second"]
>>> str3 = "he is doing his first year graduation"
>>> ans = reduce(lambda n, (old, new): n.replace(old, new), zip(str1,str2), str3)
>>> ans
'he was doing hwas second year graduation'

但是,我认为您的原创设计"his"会变为"hwas",因此您可能仍需要按照其他人的建议使用re.sub

>>> import re
>>> ans = reduce(lambda n, (old, new): re.sub(r'\b{}\b'.format(old), new, n), zip(str1,str2), str3)
>>> ans
'he was doing his second year graduation'

答案 2 :(得分:0)

@ alfasin的答案的另一种方法是枚举列表,这会产生相同的最终结果!另请注意,在for循环的每次迭代中都会覆盖str3,不使用str4变量

str1 = ["is" , "first"]       
str2 = ["was" , "second"]          
str3 = "he is doing his first year graduation"       
for idx, s in enumerate(str1):      
    str3 = str3.replace(s,str2[idx])  

print str3  # he was doing hwas second year graduation

答案 3 :(得分:-1)

这不是一个不可变性的问题。你继续创建一个只有最新替换的新str4。您想要创建一次str4,并将其更新几次。例如

str1 = ["is", "first"]
str2 = ["was", "second"]
str3 = "he is doing his first year graduation"
str4 = str3
for i in range(len(str1)):
    str4 = str4.replace(str1[i], str2[i])

你会注意到这有一个错误,其中“他的”成为“hwas”(我认为这是一个错误)。您可以使用正则表达式来匹配单词,但您可能最好使用词典。

为每个i创建一个带有{str1 [i]:str2 [i]}的字典。然后遍历str3中的每个单词,将其替换为字典中的值。