从 Python 中的 stdin 读取整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16867405/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading in integer from stdin in Python
提问by Phil Kurtis
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.
我有以下一段代码,我从 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()
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.
我不确定问题是什么。
采纳答案by Martijn Pieters
You are passing a string to the bin()function:
您正在向bin()函数传递一个字符串:
>>> 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():
通过将raw_input()结果变为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)
回答by James Holderness
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())
回答by Mike Müller
It is raw input, i.e. a string but you need an int:
它是原始输入,即一个字符串,但您需要一个 int:
bin_n = bin(int(n))
回答by Tomá? Divi?
bintakes integer as parameter and you are putting string there, you must convert to integer:
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()

