python - 使用字典更改 python 中的字符串

标签 python string dictionary

我目前有一本莫尔斯电码字母字典,我希望能够将用户输入的字符串更改为相应的莫尔斯电码字符。有什么简单的方法可以在 python 中完成此操作吗?

最佳答案

morse = {"A": ".-", "B": "-...", "C": "-.-."} #etc.
text = "ABC"
output = " ".join(morse[letter] for letter in text)

如果输入也可以小写,您可能想要使用 letter.upper()。如果您的表中没有所有莫尔斯字符,您可能也想对此进行补偿(为此感谢 ThiefMaster!),因此最终结果可能是

output = " ".join(morse[letter] for letter in text.upper() if letter in morse)

关于python - 使用字典更改 python 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4931939/

相关文章:

python - 使用 web.py 作为非阻塞 http 服务器

python - scipy 最小化约束

python - 根据python中的逻辑数组设置数组的值

c++ - 在 C++ 中将 std::string 转换为 Unicode 字符串

c - 使用循环替换字符串中的每个字母

HTML/CSS : making map 100% height for any monitor

iphone - 使用 MapKit 在 map 中的 pin(注释)标注中显示自定义 UIView

python - Django render_to_string 行为

python - 在 python 文件中插入文档字符串属性

c# - 为什么我的{get; private set} 变量返回一个空字典?