1

I have a string and 2 arrays like below:

st="a1b2c3d"
arr1 = ['1','2','3']
arr2 = ['X','Y','Z']

I want to replace all the value of '1', '2', '3' to 'X', 'Y', 'Z'. The final string will look like:

'aXbYcZd'

So I wrote this for loop:

for i in range(0, len(arr1)):
    st.replace(str(arr1[i]),str(arr2[i]))

The result is:

'aXb2c3d'
'a1bYc3d'
'a1b2cZd'

How to correctly do what I want above?

Thanks!

3 Answers 3

2

Use zip() to iterate through two lists simultaneously to replace values:

st = "a1b2c3d"
arr1 = ['1','2','3']
arr2 = ['X','Y','Z']

for x, y in zip(arr1, arr2):
    st = st.replace(x, y)

print(st)
# aXbYcZd

str.replace() does not replace a string in-place. You need to assign returned value back to a variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I choose yours as the solution since it fit my case. I have array of more than 100 string element as html img tag that I want to replace to just the name of images itself.
2

If you're replacing characters, instead of the inefficient replace loop use str.translate with str.maketrans:

>>> table = str.maketrans('123', 'XYZ')
>>> result = 'a1b2c3d'.translate(table)
>>> result
'aXbYcZd'

maketrans requires 2 strings as arguments. If you really have a list, you can use ''.join(l) to make it into a suitable string. You need to make the table only once.

The efficiency is but one point. str.translate is the way to do this correctly in cases where you will map a => b and b => something else. If you want to replace strings then you might need to use re.sub instead.

1 Comment

Nice efficiency and use of lesser-known builtins.
0

Calling replace over and over means you have to iterate through the entire string for each replacement, which is O(m * n). Instead:

rep = dict(zip(arr1, arr2)) # make mapping, O(m)
result = ''.join(rep.get(ch, ch) for ch in st)

The first line is O(m), where m is the length of arr1 and arr2.

The second line is O(n), where n is the length of st.

In total this is O(m + n) instead of O(m * n), which is a significant win if either m or n is large.

2 Comments

This solution is beautiful and efficiency, however it only works with character right? My arrays have are more than 100 element as html string so it didnt work. Thank you!
@hafiddle that's correct. Next time please provide a slightly more realistic set of example inputs. All the examples in your question used single characters, so that's what I wrote my code to handle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.