Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters of a string by a given string

Tags:

python

string

Given this string 'www__ww_www_'

I need to replace all the '_' characters with characters from the following string '1234'. The result should be 'www12ww3www4'.

TEXT = 'aio__oo_ecc_'
INSERT = '1234'

insert = list(INSERT)
ret = ''

for char in TEXT:
    if char == '_':
        ret += insert[0]
        insert.pop(0)
    else:
        ret += char

print (ret)
>> aio12oo3ecc4

What is the right way to do this? Because this seems like the most inefficient way.

like image 743
thithien Avatar asked Nov 17 '25 18:11

thithien


1 Answers

You can loop over the TEXT using a list comprehension that uses a ternary to select from an INSERT iterator or from the current element in TEXT:

>>> TEXT = 'aio__oo_ecc_'
>>> INSERT = '1234'
>>> it = iter(INSERT)
>>> "".join([next(it) if x == "_" else x for x in TEXT])
'aio12oo3ecc4'

The benefits include avoiding Shlemiel the Painter's Algorithm with ret += char. Also, pop(0) requires the whole list to be shifted forward, so it's linear (better would be reversing INSERT and using pop()).

In response to some of the comments here, list comprehensions tend to be faster than generators when the whole iterable will be consumed on the spot.

like image 72
ggorlen Avatar answered Nov 19 '25 09:11

ggorlen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!