我有以下代码,我从stdin中取一个整数n,将其转换为二进制,反转二进制字符串,然后转换回整数并输出它。
import sys
def reversebinary():
n = str(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()
但是,我收到了这个错误:
Traceback (most recent call last):
File "reversebinary.py", line 18, in <module>
reversebinary()
File "reversebinary.py", line 14, in reversebinary
bin_n = bin(n)[2:]
TypeError: 'str' object cannot be interpreted as an index
我不确定问题是什么。
答案 0 :(得分:7)
您正在将字符串传递给bin()
函数:
>>> bin('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an index
改为给它一个整数:
>>> bin(10)
'0b1010'
将raw_input()
结果转为int()
:
n = int(raw_input())
提示:你可以通过给它一个负片大步来轻松地反转一个字符串:
>>> 'forward'[::-1]
'drawrof'
所以你可以简化你的功能:
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = bin_n[::-1]
return int(revbin, 2)
甚至:
def reversebinary():
n = int(raw_input())
return int(bin(n)[:1:-1], 2)
答案 1 :(得分:3)
您希望将输入转换为整数而不是字符串 - 它已经是一个字符串。所以这一行:
n = str(raw_input())
应该是这样的:
n = int(raw_input())
答案 2 :(得分:1)
它是原始输入,即字符串,但您需要一个int:
bin_n = bin(int(n))
答案 3 :(得分:0)
bin
将整数作为参数,你将字符串放在那里,你必须转换为整数:
import sys
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()