python字符串转浮点数,Python将字符串文字转换为浮点数

I am working through the book "Introduction to Computation and Programming Using Python" by Dr. Guttag. I am working on the finger exercises for Chapter 3. I am stuck. It is section 3.2, page 25. The exercise is: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sume of the numbers in s.

The previous example was:

total = 0

for c in '123456789':

total += int(c)

print total.

I've tried and tried but keep getting various errors. Here's my latest attempt.

total = 0

s = '1.23,2.4,3.123'

print s

float(s)

for c in s:

total += c

print c

print total

print 'The total should be ', 1.23+2.4+3.123

I get ValueError: invalid literal for float(): 1.23,2.4,3.123.

解决方案

Floating point values cannot have a comma. You are passing 1.23,2.4,3.123 as it is to float function, which is not valid. First split the string based on comma,

s = "1.23,2.4,3.123"

print s.split(",") # ['1.23', '2.4', '3.123']

Then convert each and and every element of that list to float and add them together to get the result. To feel the power of Python, this particular problem can be solved in the following ways.

You can find the total, like this

s = "1.23,2.4,3.123"

total = sum(map(float, s.split(",")))

If the number of elements is going to be too large, you can use a generator expression, like this

total = sum(float(item) for item in s.split(","))

All these versions will produce the same result as

total, s = 0, "1.23,2.4,3.123"

for current_number in s.split(","):

total += float(current_number)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值