python int转float_将字符串转换为int或float在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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值