让python使用任何符号';s输入
我在做一个能把数字转换成钢琴键的代码 ***很抱歉造成混淆,我的意思是让python使用任何符号';s输入,python,python-3.x,input,symbols,Python,Python 3.x,Input,Symbols,我在做一个能把数字转换成钢琴键的代码 ***很抱歉造成混淆,我的意思是“3.14159ABC265”的理想输出是“E1\uc1 F1 C1 G1 D2\uuuud1 A2 G1”,但是当输入有#、\、或其他内容时,python会给出错误 代码: numbers = str(input('This code will convert numbers to piano keys, \nnow input any numbers here')) keys = str('') while len
“3.14159ABC265”
的理想输出是“E1\uc1 F1 C1 G1 D2\uuuud1 A2 G1”
,但是当输入有#、\、或其他内容时,python会给出错误
代码:
numbers = str(input('This code will convert numbers to piano keys, \nnow input any numbers here'))
keys = str('')
while len(numbers) == str(0):
G = str('_ ')
if numbers[0] == str(0): G='B1 '
if numbers[0] == str(1): G='C1 '
if numbers[0] == str(2): G='D1 '
if numbers[0] == str(3): G='E1 '
if numbers[0] == str(4): G='F1 '
if numbers[0] == str(5): G='G1 '
if numbers[0] == str(6): G='A2 '
if numbers[0] == str(7): G='B2 '
if numbers[0] == str(8): G='C2 '
if numbers[0] == str(9): G='D2 '
keys += G
numbers = numbers[1:len(numbers)]
print(keys)
此代码已在运行,但在输入有\、#或其他内容时无法运行。我搜索了一会儿,但没有找到答案
顺便说一句,我认为python应该有一个选项,在像这样的短代码中禁用数字和字符串之间的差异XD您可以使用
ord
将任何字符转换为数字(基于),然后使用除法和余数将数字映射为钢琴键数字和音阶,然后使用chr
将按键数字转换为字母表。下面是一个单线示例:
>>> ' '.join(map(lambda c: chr(ord('A') + int((ord(c) - ord(' ')) % 7)) + str(int((ord(c) - ord(' ')) / 7)), input()))
3.14159ABC265
'F2 A2 D2 G2 D2 A3 E3 F4 G4 A5 E2 B3 A3'
>>>