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

• 0
点赞
• 0
收藏
• 0
评论
07-12 2万+
06-30 6751
09-20 1494
03-21 1620
05-14 8709
08-16 240
06-02 5万+
06-09 3万+
11-28 5万+

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助