Reading in integer from stdin in Python

I have the following code snippet in which I take the integer n from stdin, convert it to binary, reverse the binary string, and then convert back to the integer and print it.

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() 

However, I get this error:

 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 

I am not sure what the problem is.

+4
source share
4 answers

You pass the line to bin() :

 >>> bin('10') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object cannot be interpreted as an index 

Instead, give it an integer:

 >>> bin(10) '0b1010' 

turning the result of raw_input() into int() :

 n = int(raw_input()) 

Tip. You can easily change the line by giving it a negative step in the fragment:

 >>> 'forward'[::-1] 'drawrof' 

to simplify your function:

 def reversebinary(): n = int(raw_input()) bin_n = bin(n)[2:] revbin = bin_n[::-1] return int(revbin, 2) 

or even:

 def reversebinary(): n = int(raw_input()) return int(bin(n)[:1:-1], 2) 
+7
source

You want to convert the input to an integer, not a string - it is already a string. So this line:

 n = str(raw_input()) 

should be something like this:

 n = int(raw_input()) 
+3
source

This is the original input, i.e. string, but you need int:

 bin_n = bin(int(n)) 
+1
source

bin takes an integer value as a parameter, and you put a string there, you must convert to an integer:

 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() 
0
source

Source: https://habr.com/ru/post/1483885/


All Articles