Reading in integer from stdin in Python

痞子三分冷 提交于 2019-11-30 09:15:12

问题


I have the following piece of code where I take in an integer n from stdin, convert it to binary, reverse the binary string, then convert back to integer and output 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'm getting 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'm unsure what the problem is.


回答1:


You are passing a string to the bin() function:

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

Give it a integer instead:

>>> bin(10)
'0b1010'

by turning the raw_input() result to int():

n = int(raw_input())

Tip: you can easily reverse a string by giving it a negative slice stride:

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

so you can simplify your function to:

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)



回答2:


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

n = str(raw_input())

should be something like this:

n = int(raw_input())



回答3:


It is raw input, i.e. a string but you need an int:

bin_n = bin(int(n))



回答4:


bin takes integer as parameter and you are putting string there, you must convert to 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()


来源:https://stackoverflow.com/questions/16867405/reading-in-integer-from-stdin-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!