我目前有一个莫尔斯码字母的字典,我希望能够将用户输入字符串更改为相应的莫尔斯码字符。有没有简单的方法来完成这个python?使用字典在Python中更改字符串
1
A
回答
6
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)
+0
你的测试也需要`如果letter.upper()在morse`中,否则小写不会被翻译。 – Duncan 2011-02-08 10:52:14
+0
@Duncan:对,谢谢!不过,我有一个更好的主意。 – 2011-02-08 10:53:30
2
newStr = ' '.join(morseDict[c] for c in oldStr if c in morseDict)
这将默默删除所有不是密钥的字符morseDict
编辑:现在在“字母”之间添加空格。您需要将' '
映射到一个制表符或多个空格来分隔字词。
0
morse = {
"a": ".-",
"b": "-...",
"c": "-.-.",
...
...
}
str = "Hello"
for ch in str:
print morse[ch.lower()],
0
这很容易:
input = 'a string'
morse_code = { ... }
print ' '.join([morse_code[i] for i in input])
相关问题
- 1. Python字符串字典
- 2. 在字典查找中使用Python列表或字符串?
- 3. 用Java拆分Python字典字符串
- 4. Python - 搜索字典中的字符串
- 5. 在Python中更改字典/键
- 6. 更改python中字符串的顺序
- 7. 更换使用字符串的字典中的一些短语一些字符串在Python
- 8. 使用Unicode字符串转换成字典在Python
- 9. 使用python字典从字符串中创建flashcards
- 10. Python字符串格式与字典
- 11. Python多级字典到字符串
- 12. 将字符串转换为python字典
- 13. Python将字符串转换为字典
- 14. python字典从字符串转换?
- 15. 将python字典转换为字符串
- 16. Python字符串和字典解析
- 17. 字符串到字典列表(python)
- 18. Python将字符串放入字典
- 19. 在Python中更新字典
- 20. 在Python中更新字典
- 21. 将字符串映射到一组字符串的Python字典?
- 22. 如何更改字符串中某个位置的字符...... Python
- 23. 更改字符串
- 24. 使用字符串作为字典键?
- 25. 使用字符串查找C#字典
- 26. 更改字典中的值python 2.7
- 27. Python更改字符串变量的值
- 28. 更改字典
- 29. Python:如何让字符串格式使用字典查找?
- 30. 在c#中将字典转换为字典中的字符串<字符串,字典<string,int>>?
你有什么,到目前为止,怎么不工作? – 2011-02-08 10:33:09