【发布时间】:2016-06-06 08:18:21
【问题描述】:
我目前有一个将英语翻译成莫尔斯电码的代码。它工作正常,但我想添加另一个参数,允许程序在输入数字或标点符号时打印###。
translation_table = [["a",".-"],["b","-..."],["c","-.-."],["d","-.."],
["e","."],["f","..-."],["g","--."],["h","...."],
["i",".."],["j",".---"],["k","-.-"],["l",".-.."],
["m","--"],["n","-."],["o","---"],["p",".--."],
["q","--.-"],["r",".-."],["s","..."],["t","-"],
["u","..-"],["v","...-"],["w",".--"],["x","-..-"],
["y","-.--"],["z","--.."]]
word_index = 0
english = input("Enter a sentence to be translated(*** to end): ")
words = list(english)
translated_sentence = ""
while word_index < len(words):
if english == "***":
print("Program has ended")
break
translation_index = 0
while translation_index < len(translation_table):
if translation_table[translation_index][0] == words[word_index]:
translated_sentence = translated_sentence + translation_table[translation_index][1]
translation_index = 27
elif words[word_index] == " ":
translated_sentence = translated_sentence + " "
translation_index = 27
else :
translation_index = translation_index + 1
我正在考虑添加另一个类似于
的 elif 行elif words[word_index][0] == :
translated_sentence = translated_sentence + "###"
translation_index = 27
但我不知道如何让它只检查字符串中的数字和标点符号。例如,hi! 将打印 .....###。
谢谢
【问题讨论】:
标签: list python-3.x if-statement