python字符串替换函数参数
由于不可变属性,只有第二次更改(“第一次”更改为“第二次”)。如何同时进行这两项更改。实际上我有一根很大的绳子。我是python新手,请帮助我将最后一行指定给str3:python字符串替换函数参数,python,Python,由于不可变属性,只有第二次更改(“第一次”更改为“第二次”)。如何同时进行这两项更改。实际上我有一根很大的绳子。我是python新手,请帮助我将最后一行指定给str3: str1 = ["is" , "first"] str2 = ["was" , "second"] str3 = "he is doing his first year graduation" for i in RANGE(len(str1)): str4 = str3
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])
注意,单词“his”中的is也被替换了
如果需要“精确”匹配,请使用正则表达式模块:
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
@alfasin回答的另一种方法是枚举列表,这会产生相同的最终结果!另外,请注意,str3在
for
循环的每次迭代中都会被覆盖,没有使用str4
变量
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
这不是一个不变性的问题。您一直在创建一个新的str4,只使用最新的替换。您想创建一次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
你会注意到这有一个bug,其中“his”变成了“hwas”(我想这是个bug)。您可以使用正则表达式只匹配单词,但最好使用字典
为每个i创建一个带有{str1[i]:str2[i]}的字典。然后迭代str3中的每个单词,并将其替换为字典中的值。您可以在一行中应用
reduce
和lambda
:
ans=reduce(lambda n,(旧的,新的):n.replace(旧的,新的),zip(str1,str2,str3)
例如:
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])
但是,我想在您的原始设计中,“his”将成为“hwas”
,因此您可能仍然需要按照其他人的建议使用re.sub
:
>>> 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'
@Harvey
izip()
不会生成列表
,因此它不应该适合reduce()
函数,对吗?它返回一个iterable,这就是reduce所需的全部内容。Python3的zip()实际上是Python2的itertools.izip()<代码>从itertools导入izip;打印(减少(λx,y:x+“”。连接(y),izip(“abc”,“123”),“”)printsa1b2c3
>>> 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'