N
N
Nazarius2020-08-16 02:26:45
Python
Nazarius, 2020-08-16 02:26:45

How to replace words in a string?

There is text:
text = "Hello lolo lo!"
I need to somehow replace the word "lo" with the word "lol"
I did it through replace () and it came out: "Hellol lollol lol".
And it is necessary that in the end it becomes: ""Hello lolo lol!""
Preferably without libraries.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey, 2020-08-16
@Nazarius

Crooked, rude, the cycle is made from the bulldozer, but on the knee I propose this approach:

s = "Hello lolo lo!"
lst = s.replace('!', '').split()
print(lst)

i = int(0)
for el in lst:
    if lst[i] == 'lo': lst[i] = 'лол'
    i+=1
print(lst)

I think you can modify it however you like.

A
Alexander Sidorevich, 2020-08-16
@alexandersidorevitch

There are some stupid ways

text.replace('lo!', ' лол!')

text[::-1].replace('lo'[::-1], 'лол', 1)[::-1]

It's better to use this method:
re.sub(r'\blo\b', 'лол', text)

But you want without libraries...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question