1
votes

I have an input string from user and I want to translate it according to the keys in my dictionary. And I want to write it not line by line:

dict{"a":"bla", "b": "gla", "c":cla"}

user_text = input("Write your text: ")

If the user writes acab, the desired output should be like this:

bla cla bla gla

So far I either get bla, cla, gla, or it doesn't recognize the key, as there is no such acab, only a or b or c and now I hope you see my problem...

I think I should use loops.

4
Would you mind explaining it maybe with a better example or some of the sample code you've written. Can't understand what your final outcome should be (if there is a pattern could you pls state that too)Aryan Garg
I will try, but I do not want to copy the exact exercise, it could spoil all the fun for next students :) However, let's say it is a traslation of a text to cipher code. You know - the one with dots and dashes :) So - you ask user for an input. He writes a text in normal alphabet and we want to get the result in the cipher: User writes "hello", he gets: .... . .-.. .-.. ---Kristyna Sodomkova

4 Answers

0
votes

You can join the elements of a comprehension list as follows:

user_text="acab"
d = {"a": "bla", "b": "gla", "c": "cla"}
res = " ".join([d[v] for i,v in enumerate(user_text)])
0
votes
dict={"a":"bla", "b": "gla", "c":cla"}
user_text = input("Write your text: ")
s=""
for i in user_text:
      try:
        s+=dict[i]+" "
      except:
        print("such key does not exist")

print("desired output=",s)

you can use a for loop to access each element of the user_text string and add it to a string s

0
votes
for text in user_text:
    out = out + " "+ dict.get(text)
print(out.strip())
0
votes

Finally it works perfect

dict{"a":"bla", "b": "gla", "c":cla"}

dict[" "] = "/"

requested_text = input("Write your text here: ")

for m in requested_text:
    print(morseCode[m], end='  ')