简体   繁体   English

在Python 3中将字符串转换为int或float?

[英]Convert strings to int or float in Python 3?

 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. 我对编程很新,我的背景主要是C#的基础知识到目前为止。 I wanted to try to learn Python through doing all my C# school projects on Python. 我想通过在Python上完成我所有的C#学校项目来学习Python。 I'm used to the simple syntax of C# which would look something like this: 我习惯了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. 我试图发现自己的格式与我在C#中习惯使用的格式类似,但是在找到一个方法将用户输入字符串转换为整数后,所有这些谷歌搜索并尝试一切我能想到(我在谷歌上发现)我觉得是时候问了。 Can you help? 你能帮我吗?

You have to convert the integer into a string: 您必须将整数转换为字符串:

print('2 + ' + str(integer) + ' = ' + str(rslt))

Or pass it as an argument to print and print will do it for you: 或者将其作为参数传递给print和打印将为您完成:

print('2 +', integer, '=', rslt)

I would do it using string formatting: 我会使用字符串格式化:

print('2 + {} = {}'.format(integer, rslt))

Your problem is not with converting the input to an integer. 您的问题不是将输入转换为整数。 The problem is that when you write ' = ' + rslt you are trying to add an integer to a string, and you can't do that. 问题是当你写' = ' + rslt你试图在字符串中添加一个整数,而你不能这样做。

You have a few options. 你有几个选择。 You can convert integer and rslt back into strings to add them to the rest of your string: 您可以将integerrslt转换回字符串,将它们添加到字符串的其余部分:

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

In Python 3.x - input is 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 int or float : 另一个选项 - 看起来有点复杂是允许解释器对值进行最佳猜测,然后提出不是intfloat东西:

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... 如果你想要复杂的数字或列表或元组作为输入,这允许更多的灵活性......

If you want to convert a value to an integer, use the int built in function, and to convert a value to a floating point number, use the float built in function. 如果要将值转换为整数,请使用int内置函数,并将值转换为浮点数,请使用float built in函数。 Then you can use the str built in function to convert those values back to strings. 然后,您可以使用str内置函数将这些值转换回字符串。 The built in function input returns strings, so you would use these functions in code like this: 内置函数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)
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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM