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

03-25 1万+
07-12 2万+
11-13 2165
06-30 6751
09-20 1494
02-19 7994
10-03 499
03-21 1620
05-14 8709
11-21 362
08-16 240
12-29 884
11-26 1400
07-17 5万+
06-02 5万+
06-09 3万+
11-28 5万+

### “相关推荐”对你有帮助么？

•  非常没帮助
•  没帮助
•  一般
•  有帮助
•  非常有帮助 被折叠的  条评论 为什么被折叠? 到【灌水乐园】发言 点击重新获取   扫码支付 1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。 余额充值