首页 > 解决方案 > 如果包含子字符串,则使用替换更改整个字符串

问题描述

a = “thanklynette i owe you one best regardsjohn”
b = [(“lynette”,”john”)]

for i in b:
    a.str.replace(b,’’)
print(a)

我收到一个类型错误,因为替换不接受列表。有办法解决吗?我想要的输出是

a = “i owe you one best” 

或者

a = “thank i owe you one best regards”

标签: stringfor-loopreplacesubstringhelper

解决方案


我不确定为什么名称在列表中的元组中,如果它不是重要的部分,你可以这样做。您的代码试图a用列表b而不是其中的值替换。

a = 'thanklynette i owe you one best regardsjohn'
b = ['lynette','john']
s = a
for i in b:
    s = s.replace(i," ")
print(s)

但是,如果元组按照格式很重要,您可以包含一个嵌套循环来访问每个元素。

for i in b:
    for j in i:
        s = s.replace(j," ")

输出

thank  i owe you one best regards 

推荐阅读