在 Python 3 中将字符串转换为 int 或 float?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15444945/
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
Convert strings to int or float in Python 3?
提问by Rabcor
integer = input("Number: ")
rslt = int(integer)+2
print('2 + ' + integer + ' = ' + rslt)
double = input("Point Number: ")
print('2.5 + ' +double+' = ' +(float(double)+2.5))
Gives me
给我
Traceback (most recent call last):
File "C:\...", line 13, in <module>
print('2 + ' + integer + ' = ' + rslt)
TypeError: Can't convert 'int' object to str implicitly
I'm fairly new to programming and my background is mostly just the basics of C# so far. I wanted to try to learn Python through doing all my C# school projects on Python. I'm used to the simple syntax of C# which would look something like this:
我对编程还很陌生,到目前为止,我的背景主要只是 C# 的基础知识。我想通过在 Python 上完成我所有的 C# 学校项目来尝试学习 Python。我习惯了 C# 的简单语法,它看起来像这样:
int integer = Convert.ToInt32(Console.ReadLine())
or
或者
double double = Convert.ToDouble(Console.ReadLine())
Which takes a user input string and converts it to what I specified.
它接受用户输入字符串并将其转换为我指定的内容。
I think I read py2.x has a command called raw_input that works a bit better than the input command of py3.x in this regard.
我想我读过 py2.x 有一个名为 raw_input 的命令,它在这方面比 py3.x 的输入命令好一点。
I was trying to find myself a similar format as the one I'm used to in C# to use in Python, but it's proving surprisingly hard just to find a method to convert the user input string into an integer after all this googling and trying everything I could think of (and that I found on google) I decided it was time to ask. Can you help?
我试图找到一种与我在 C# 中习惯于在 Python 中使用的格式类似的格式,但事实证明,在所有这些谷歌搜索并尝试所有这些之后,仅仅找到一种将用户输入字符串转换为整数的方法是非常困难的我能想到(我在谷歌上找到的)我决定是时候问了。你能帮我吗?
回答by Blender
You have to convert the integer into a string:
您必须将整数转换为字符串:
print('2 + ' + str(integer) + ' = ' + str(rslt))
Or pass it as an argument to printand print will do it for you:
或者将其作为参数传递给print并打印将为您完成:
print('2 +', integer, '=', rslt)
I would do it using string formatting:
我会使用字符串格式来做到这一点:
print('2 + {} = {}'.format(integer, rslt))
回答by BrenBarn
Your problem is not with converting the input to an integer. The problem is that when you write ' = ' + rsltyou are trying to add an integer to a string, and you can't do that.
您的问题不在于将输入转换为整数。问题在于,当您编写代码时,' = ' + rslt您试图将一个整数添加到字符串中,而您不能这样做。
You have a few options. You can convert integerand rsltback into strings to add them to the rest of your string:
你有几个选择。您可以转换integer并rslt返回字符串以将它们添加到字符串的其余部分:
print('2 + ' + str(integer) + ' = ' + str(rslt))
Or you could just print multiple things:
或者你可以只打印多个东西:
print('2 + ', integer, ' = ', rslt)
Or use string formatting:
或者使用字符串格式:
print('2 + {0} = {1}'.format(integer, rslt))
回答by Jon Clements
In Python 3.x - inputis the equivalent of Python 2.x's raw_input...
在 Python 3.x 中 -input相当于 Python 2.x 的raw_input...
You should be using string formatting for this - and perform some error checking:
您应该为此使用字符串格式 - 并执行一些错误检查:
try:
integer = int(input('something: '))
print('2 + {} = {}'.format(integer, integer + 2))
except ValueError as e:
print("ooops - you didn't enter something I could make an int of...")
Another option - that looks a bit convoluted is to allow the interpreter to take its best guess at the value, then raise something that isn't intor float:
另一种选择 - 看起来有点令人费解的是让解释器对值进行最佳猜测,然后提出一些不是int或的东西float:
from ast import literal_eval
try:
value = literal_eval(input('test: '))
if not isinstance(value, (int, float)):
raise ValueError
print value + 2
except ValueError as e:
print('oooops - not int or float')
This allows a bit more flexibility if you wanted complex numbers or lists or tuples as input for instance...
例如,如果您想要复数或列表或元组作为输入,这将提供更大的灵活性...
回答by murgatroid99
If you want to convert a value to an integer, use the intbuilt in function, and to convert a value to a floating point number, use the floatbuilt in function. Then you can use the strbuilt in function to convert those values back to strings. The built in function inputreturns strings, so you would use these functions in code like this:
如果要将值转换为整数,请使用int内置函数,而要将值转换为浮点数,请使用float内置函数。然后您可以使用str内置函数将这些值转换回字符串。内置函数input返回字符串,因此您可以在代码中使用这些函数,如下所示:
integer = input("Number: ")
rslt = int(integer)+2
print('2 + ' + integer + ' = ' + str(rslt))
double = input("Point Number: ")
print('2.5 + ' +str(double)+' = ' +str(float(double)+2.5)
回答by jurgenreza
integer = int(input("Number: "))
print('2 + %d = %d' % (integer, integer + 2))
double = float(input("Point Number: "))
print('2.5 + %.2f = %.2f' % (double, double + 2.5))

