将字符串转换为int或float在python 3? [英] Convert strings to int or float in python 3?
问题描述
print('2 +'+ integer +'='+
print('2.5 +'+ double +'='+(float(double)+2.5))
给我
追溯(最近call last):
文件C:\ ...,第13行,< module>
print('2 +'+ integer +'='+ rslt)
TypeError:不能将'int'对象转换为隐式
我对编程相当新鲜,我的背景大多只是C#的基础知识。我想通过在python上完成我所有的C#学校项目来尝试学习python。我习惯了C#的简单语法,看起来像这样。
int integer = Convert.ToInt32(Console。 ReadLine())
或
double double = Convert.ToDouble(Console.ReadLine())
这需要用户输入字符串并将其转换为我指定的。
我想我读取py2.x有一个命令raw_input,比输入命令好一点的py3.x在这方面。
我试图找到一个类似的格式,我习惯于在C#中使用python,但它是令人惊讶的很难找到一种方法来将用户输入字符串转换为一个整数,所有这些谷歌搜索和尝试我可以想到的一切(我发现在谷歌),我决定是时候问了。你可以帮助吗?
你必须将整数转换为字符串:
print('2 +'+ str(integer)+'='+ str(rslt))
或作为参数传递给 print
,打印将为您做:
print('2 +',integer,'=',rslt)
我会使用字符串格式化:
print('2 + {} = {}'。format(integer,rslt))
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.
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.
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?
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('2 +', integer, '=', rslt)
I would do it using string formatting:
print('2 + {} = {}'.format(integer, rslt))
这篇关于将字符串转换为int或float在python 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!