0

I am creating a script that translates certain characters with directions, and any character that is not one of the known characters is replaced with "Aaaaah!".

string = input('Terrain: ')
for letters in string:
  letters = letters.replace('r', 'right')
  letters = letters.replace('l', 'left')
  letters = letters.replace('j', 'jump')
  letters = letters.replace('s', 'straight')
  print(letters)
  • 3
    Hi Mark, what is the question? – Luis Rico Aug 05 '19 at 07:45
  • you can use regex. visit this: https://stackoverflow.com/questions/11475885/python-replace-regex – Ali dashti Aug 05 '19 at 07:47
  • I am not sure you are looking for `replace`ing... according to your example you simply loop the input and check what is each character. Why even replace? – Tomerikoo Aug 05 '19 at 07:47
  • Just make sure you dont replace the string 'r' as last... Must say that it is quite error prone. But whatever floats your boat – zwep Aug 05 '19 at 07:47
  • Question:In rally driving, it's important to know what terrain is coming up on the route. The navigator reads out pacenotes, written in shorthand, so the driver knows what to expect. We've developed a simplified pacenote system for our robotic navigator for a slot car set, using the following shorthand:Write a program that reads in the terrain, and prints out the course notes. If the pacenotes include an unknown shorthand, our robot navigator should panic and print out: Aaaaah! – Mark Ingram Aug 05 '19 at 07:47
  • 1
    So why `replace`? just use `if/else` on the input... `if letters not in ('l', 'r', 'j', 's'): print("Aaaaah!")` – Tomerikoo Aug 05 '19 at 07:48
  • Anyway if you *__really__* want to replace, use regex: `re.sub("[^lrjs]", "Aaaaaah!", string)` – Tomerikoo Aug 05 '19 at 07:52

1 Answers1

2

Use dict and dict.get:

my_dict = {'r': 'right', 'l': 'left', 'j': 'jump', 's': 'straight'}

# string = input('Terrain: ')
string = 'rljsZ' # For test purpose

new_string = ''.join(map(lambda x:my_dict.get(x, 'Aaaaah!'), string))
print(new_string)

Output:

'rightleftjumpstraightAaaaah!'
Chris
  • 29,127
  • 3
  • 28
  • 51