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)
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With