使用替换字符串数组
Using replace with an array of strings
我想执行以下操作:
thing = "hello world"
A = ["e","l"]
B = ["l","e"]
newthing = thing.replace(A,B)
print(newthing)
那么输出应该是 hleeo wored,但似乎不允许我使用数组替换作为输入。有没有办法还能这样呢?
这会起作用:
newthing = thing
for a,b in zip(A, B):
newthing = newthing.replace(a, b)
这是我的想法。
thing = "hello world"
A = ["e","l"]
B = ["l","e"]
def replace_test(text, a, b):
_thing = ''
for s in text:
if s in a:
for i, val in enumerate(a):
if s == val:
s = b[i]
break
_thing += s
return _thing
newthing = replace_test(thing, A, B)
print(newthing)
#>> hleeo wored
我想执行以下操作:
thing = "hello world"
A = ["e","l"]
B = ["l","e"]
newthing = thing.replace(A,B)
print(newthing)
那么输出应该是 hleeo wored,但似乎不允许我使用数组替换作为输入。有没有办法还能这样呢?
这会起作用:
newthing = thing
for a,b in zip(A, B):
newthing = newthing.replace(a, b)
这是我的想法。
thing = "hello world"
A = ["e","l"]
B = ["l","e"]
def replace_test(text, a, b):
_thing = ''
for s in text:
if s in a:
for i, val in enumerate(a):
if s == val:
s = b[i]
break
_thing += s
return _thing
newthing = replace_test(thing, A, B)
print(newthing)
#>> hleeo wored