1

How Would I change this function from changing only the letters to change the entire word? I believe I have to change the ch in the code (for ch in newString: ) but I don't know what to.

replacements = {
'TOMORROW': 'TMR',
'ABOUT': 'BOUT',
'PLEASE': 'PLZ',
'BEFORE': 'B4'
}

def replace(newString):
old,new = [],[]
for ch in newString:
    if replacements.get(ch):
        newString = newString.replace(ch, replacements.get(ch))
    print(newString)
aminography
  • 21,986
  • 13
  • 70
  • 74
Blame
  • 29
  • 3
  • Possible duplicate of [How to replace words in a string using a dictionary mapping](https://stackoverflow.com/questions/49600700/how-to-replace-words-in-a-string-using-a-dictionary-mapping) – kaya3 Nov 15 '19 at 04:04

2 Answers2

0

You can simply split the string on space and it will be easy then

replacements = {
'TOMORROW': 'TMR',
'ABOUT': 'BOUT',
'PLEASE': 'PLZ',
'BEFORE': 'B4'
}

st="ABOUT last BEFORE"
li=st.split()
for i in range(len(li)):
    if li[i] in replacements:
        li[i]=replacements[li[i]]
print(" ".join(li))
Swarnveer
  • 490
  • 5
  • 23
0

You can do something like this:

replacements = {
'TOMORROW': 'TMR',
'ABOUT': 'BOUT',
'PLEASE': 'PLZ',
'BEFORE': 'B4'
}

message="ABOUT TOMORROW PLEASE SEE ME BEFORE NOON"

for word, initial in replacements.items():
    message = message.replace(word, initial)
print(message)   #--> "BOUT TMR PLZ SEE ME B4 NOON"


or backwards:

message="BOUT TMR PLZ SEE ME B4 NOON"
for word, initial in replacements.items():
    message = message.replace(initial, word)
print(message)  #--> "ABOUT TOMORROW PLEASE SEE ME BEFORE NOON"

oppressionslayer
  • 6,942
  • 2
  • 7
  • 24