Python 3 将一串键转换成值到同一行
Python 3 translating a string of keys into values into the same line
我有一个来自用户的输入字符串,我想根据我字典中的键翻译它。而且我不想逐行写:
dict{"a":"bla", "b": "gla", "c":cla"}
user_text = input("Write your text: ")
如果用户写acab
,期望的输出应该是这样的:
bla cla bla gla
到目前为止,我要么得到 bla、cla、gla,要么它无法识别密钥,因为没有这样的 acab,只有 a 或 b 或 c,现在我希望你能看到我的问题...
我想我应该使用循环。
您可以按如下方式加入理解列表的元素:
user_text="acab"
d = {"a": "bla", "b": "gla", "c": "cla"}
res = " ".join([d[v] for i,v in enumerate(user_text)])
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)
您可以使用 for
循环访问 user_text
字符串的每个元素并将其添加到字符串 s
终于完美运行了
dict{"a":"bla", "b": "gla", "c":cla"}
dict[" "] = "/"
requested_text = input("Write your text here: ")
for m in requested_text:
print(morseCode[m], end=' ')
for text in user_text:
out = out + " "+ dict.get(text)
print(out.strip())
我有一个来自用户的输入字符串,我想根据我字典中的键翻译它。而且我不想逐行写:
dict{"a":"bla", "b": "gla", "c":cla"}
user_text = input("Write your text: ")
如果用户写acab
,期望的输出应该是这样的:
bla cla bla gla
到目前为止,我要么得到 bla、cla、gla,要么它无法识别密钥,因为没有这样的 acab,只有 a 或 b 或 c,现在我希望你能看到我的问题...
我想我应该使用循环。
您可以按如下方式加入理解列表的元素:
user_text="acab"
d = {"a": "bla", "b": "gla", "c": "cla"}
res = " ".join([d[v] for i,v in enumerate(user_text)])
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)
您可以使用 for
循环访问 user_text
字符串的每个元素并将其添加到字符串 s
终于完美运行了
dict{"a":"bla", "b": "gla", "c":cla"}
dict[" "] = "/"
requested_text = input("Write your text here: ")
for m in requested_text:
print(morseCode[m], end=' ')
for text in user_text:
out = out + " "+ dict.get(text)
print(out.strip())