Home > other >  How to replace second instance of character in substring?
How to replace second instance of character in substring?

Time:06-21

I have the following strings:

text_one = str("\"A Ukrainian American woman who lives near Boston, Massachusetts, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Russian attacks on Ukraine and the fear these attacks have engendered.")

text_two = str("\n\nMany people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Russian soldiers overtake the area, the Boston-area woman said.\"")

I need to replace every instance of s/S with $, but not the first instance of s/S in a given word. So the input/output would look something like:

> Mississippi
> Mis$i$$ippi

My idea is to do something like 'after every " " character, skip first "s" and then replace all others up until " " character' but I have no idea how I might go about this. I also thought about creating a list to handle each word.

CodePudding user response:

Solution with re:

import re

text_one = '"A Ukrainian American woman who lives near Boston, Massachusetts, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Russian attacks on Ukraine and the fear these attacks have engendered.'
text_two = '\n\nMany people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Russian soldiers overtake the area, the Boston-area woman said."'


def replace(s):
    return re.sub(
        r"(?<=[sS])(\S )",
        lambda g: g.group(1).replace("s", "$").replace("S", "$"),
        s,
    )


print(replace(text_one))
print(replace(text_two))

Prints:

"A Ukrainian American woman who lives near Boston, Mas$achu$ett$, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Rus$ian attacks on Ukraine and the fear these attacks have engendered.


Many people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Rus$ian soldier$ overtake the area, the Boston-area woman said."

CodePudding user response:

The first thing you're going to want to do is to find the index of the first s

Then, you'll want to split the string so you get the string until after the first s and the rest of the string into two separate variables

Next, replace all of the s's in the second string with dollar signs

Finally, join the two strings with an empty string

test = "mississippi"
first_index = test.find("s")
tests = [test[:first_index 1], test[first_index 1:]]
tests[1] = tests[1].replace("s", "$")
result = ''.join(tests)
print(result)
  • Related