4

This is my task

journey = """Just a small tone girl
Leaving in a lonely whirl
She took the midnight tray going anywhere
Just a seedy boy
Bored and raised in South Detroit or something
He took the midnight tray going anywhere"""

Gross. Okay, so for this exercise, your job is to use Python's string replace method to fix this string up and print the new version out to the console.

This is what I did

journey = """ just a small tone girl
Leaving in a lonely whirl
she took a midnight tray going anywhere
Just a seedy boy
bored and raised in south detroit or something
He took the midnight tray going anywhere"""

journeyEdit = journey.replace("tone" , 
"town").replace("tray","train").replace("seedy","city").replace("Leaving", 
"living").replace("bored","born").replace("whirl","world").replace("or 
something", " ")

print (journeyEdit)
Sultan Singh Atwal
  • 810
  • 2
  • 8
  • 19
David
  • 55
  • 6

2 Answers2

5

Here is a sample way to replace words from text. you can use python re package.

please find the below code for your guidance.

import re
journey = """ just a small tone girl Leaving in a lonely whirl she took a 
midnight tray going anywhere Just a seedy boy bored and raised in south 
detroit or something He took the midnight tray going anywhere"""
# define desired replacements here

journeydict = {"tone" : "town",
          "tray":"train",
          "seedy":"city",
          "Leaving": "living",
          "bored":"born",
          "whirl":"world"
          }

# use these given three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in journeydict.items()) 
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest 
versions
pattern = re.compile("|".join(journeydict.keys()))
text = pattern.sub(lambda m: journeydict[re.escape(m.group(0))], journey)

print(journey)
print(text)
  • How can i use this but in a INSENSITIVE case? I tried to add the flags re.I, but I fail in the attempt – juanbits Mar 02 '20 at 19:19
2

Probably a longer way than you given ;-).

As given at How to replace multiple substrings of a string?:

import re

journey = """ just a small tone girl Leaving in a lonely whirl she took a 
midnight tray going anywhere Just a seedy boy bored and raised in south 
detroit or something He took the midnight tray going anywhere"""

rep = {"tone": "town",
       "tray": "train",
       "seedy":"city",
       "Leaving": "living",
       "bored":"born",
       "whirl":"world",
       "or something": " "}

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())

# Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))

journeyEdit = pattern.sub(lambda m: rep[re.escape(m.group(0))], journey)

print(journeyEdit)
Rahul Talole
  • 137
  • 1
  • 2
  • 9