Python将String Literal转换为Float

时间:2014-01-19 03:03:32

标签: python string literals

我正在阅读Guttag博士的“使用Python进行计算和编程简介”一书。我正在进行第3章的手指练习。我被卡住了。它是第25页的第3.2节。练习是:设s是一个包含由逗号分隔的十进制数字序列的字符串,例如s = '1.23,2.4,3.123'。编写一个打印s中数字的sume的程序。

上一个例子是:

total = 0
for c in '123456789':
    total += int(c)
print total.

我已经尝试过并尝试但仍然遇到各种错误。这是我最近的尝试。

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

我得到ValueError: invalid literal for float(): 1.23,2.4,3.123.

21 个答案:

答案 0 :(得分:7)

浮点值不能包含逗号。您正在将1.23,2.4,3.123原样传递给float函数,该函数无效。首先根据逗号分割字符串,

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

然后将该列表的每个元素和每个元素转换为float并将它们一起添加以获得结果。要感受Python的强大功能,可以通过以下方式解决此特定问题。

您可以找到total,就像这样

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

如果元素的数量太大,您可以使用生成器表达式,如此

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

所有这些版本都会产生与

相同的结果
total, s = 0, "1.23,2.4,3.123"
for current_number in s.split(","):
    total += float(current_number)

答案 1 :(得分:3)

由于您从Python开始,您可以尝试这种简单的方法:

使用split(c)函数,其中c是分隔符。有了这个,你将有一个列表numbers(在下面的代码中)。然后,您可以迭代该列表的每个元素,将每个数字转换为float(因为numbers的元素是字符串)并将它们相加:

numbers = s.split(',')
sum = 0

for e in numbers:
    sum += float(e)

print sum

<强>输出:

6.753

答案 2 :(得分:2)

第25页的使用Python计算和编程简介一书。

“设s是一个包含由逗号分隔的十进制数字序列的字符串,例如s ='1.23,2.4,3.123'。编写一个程序,用s打印数字的总和。“

如果我们只使用到目前为止所教授的内容,那么这段代码就是一种方法:

tmp = ''
num = 0
print('Enter a string of decimal numbers separated by comma:')
s = input('Enter the string: ')
for ch in s:
    if ch != ',':
        tmp = tmp + ch
    elif ch == ',':
        num = num + float(tmp)
        tmp = ''

# Also include last float number in sum and show result
print('The sum of all numbers is:', num + float(tmp))

答案 3 :(得分:2)

total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
    total = total + float(c)
print(total)

答案 4 :(得分:1)

这就是我提出的:

catch(Exception exception)

答案 5 :(得分:1)

我认为自从提出此问题以来,他们已经修订了这本教科书(其他一些人已经回答了)。我有第二版的教科书,拆分示例不在第25页上。本课之前没有任何内容。向您展示如何使用拆分。

我最终想找到使用正则表达式的另一种方式。这是我的代码:

# Intro to Python
# Chapter 3.2
# Finger Exercises

# Write a program that totals a sequence of decimal numbers
import re
total = 0 # initialize the running total
for s in re.findall(r'\d+\.\d+','1.23, 2.2, 5.4, 11.32, 18.1,22.1,19.0'):
    total = total + float(s)
print(total)

在学习新事物的过程中,我从不认为自己会变得很沉密,但是到目前为止,本书的(大部分)手指练习都很难。

答案 6 :(得分:1)

像魅力一样工作 只使用了我所学到的东西

    s = raw_input('Enter a string that contains a sequence of decimal ' +  
                   'numbers separated by commas, e.g. 1.23,2.4,3.123: ')

    s = "," + s+ "," 

    total =0

    for i in range(0,len(s)):

         if s[i] == ",":

              for j in range(1,(len(s)-i)):

                   if s[i+j] == ","
                   total  = total + float(s[(i+1):(i+j)])
                   break
     print total

答案 7 :(得分:0)

我的回答在这里:

s = '1.23,2.4,3.123'

sum = 0
is_int_part = True
n = 0
for c in s:
    if c == '.':
        is_int_part = False
    elif c == ',':
        if is_int_part == True:
            total += sum
        else:
            total += sum/10.0**n
        sum = 0
        is_int_part = True
        n = 0
    else:
        sum *= 10
        sum += int(c)
        if is_int_part == False:
            n += 1
if is_int_part == True:
    total += sum
else:
    total += sum/10.0**n
print total

答案 8 :(得分:0)

我已经成功地回答了这个问题,直到3.2循环部分

s = '1.0, 1.1, 1.2'
print 'List of decimal number' 
print s 
total = 0.0
for c in s:
    if c == ',':
       total += float(s[0:(s.index(','))])
       d = int(s.index(','))+1
       s = s[(d+1) : len(s)]

s = float(s)
total += s
print '1.0 + 1.1 + 1.2 = ', total  

这是我觉得分裂功能对你和我这样的初学者不好的问题的答案。

答案 9 :(得分:0)

考虑到您可能尚未接触到更复杂的功能,只需尝试这些功能即可。

total = 0
for c in "1.23","2.4",3.123":
    total += float(c)
print total

答案 10 :(得分:0)

我的方式有效:

s = '1.23, 211.3'
total = 0
for x in s:
    for i in x:
        if i != ',' and i != ' ' and i != '.':
            total = total + int(i)
print total

答案 11 :(得分:0)

我的回答:

s = '2.1,2.0'
countI = 0
countF = 0
totalS = 0

for num in s:
    if num == ',' or (countF + 1 == len(s)):
        totalS += float(s[countI:countF])
        if countF < len(s):
            countI = countF + 1
    countF += 1

print(totalS) # 4.1

仅当数字为浮点数时才有效

答案 12 :(得分:0)

这是一个不使用split的解决方案:

s='1.23,2.4,3.123,5.45343'
pos=[0]
total=0
for i in range(0,len(s)):
    if s[i]==',':
        pos.append(len(s[0:i]))
pos.append(len(s))
for j in range(len(pos)-1):
    if j==0:
        num=float(s[pos[j]:pos[j+1]])
        total=total+num
    else:
        num=float(s[pos[j]+1:pos[j+1]])
        total=total+num     
print total

答案 13 :(得分:0)

这是我的答案。它与上面的user5716300相似,但是由于我还是初学者,因此为拆分字符串显式创建了一个单独的变量s1:

s = "1.23,2.4,3.123"
s1 = s.split(",")      #this creates a list of strings

count = 0.0
for i in s1:
    count = count + float(i)
print(count)

答案 14 :(得分:0)

如果我们只是坚持本章的内容,那么我想到了这一点:(尽管使用theFourthEye提到的sum方法也很漂亮):

s = '1.23,3.4,4.5'
result = s.split(',')
result = list(map(float, result))
n = 0
add = 0
for a in result:
    add = add + result[n]
    n = n + 1
print(add)

答案 15 :(得分:0)

s = input('Enter a sequence of decimal numbers separated by commas: ')
x = ''
sum = 0.0
for c in s:
    if c != ',':
        x = x + c
    else:
        sum = sum + float(x)
        x = ''  
sum = sum + float(x)        
print(sum)  

这只是使用了本书中已经涵盖的思想。基本上,它遍历原始字符串s中的每个字符,使用字符串加法将每个字符添加到下一个以构建新的字符串x,直到遇到逗号为止,此时它将x的内容更改为浮点数并将其添加到以零开头的sum变量。然后,它将x重置为空字符串,并重复执行直到覆盖s中的所有字符

答案 16 :(得分:0)

我只想发布我的答案,因为我正在读这本书。

s = '1.23,2.4,3.123'

ans = 0.0
i = 0
j = 0
for c in s:
    if c == ',':
        ans += float(s[i:j])
        i = j + 1
    j += 1
ans += float(s[i:j])
print(str(ans))

答案 17 :(得分:0)

使用书中的知识:

s = '4.58,2.399,3.1456,7.655,9.343'
total = 0
index = 0
for string in s:
    index += 1
    if string == ',':
        temp = float(s[:index-1])
        s = s[index:]
        index = 0
        total += temp
        temp = 0
print(total)

在这里,我使用了字符串切片,并且每次我们的'string'变量等于','时都对原始字符串进行切片。还使用索引变量来跟踪逗号前的数字。在对字符串进行切片之后,将输入到tmp的数字清除,并在其前面加上逗号,该字符串将成为没有该数字的另一个字符串。

因此,每次发生索引变量都需要重置。

答案 18 :(得分:0)

这是我在问题中使用的确切字符串,并且只使用了迄今为止所教的内容。

total = 0
temp_num = ''

for char in '1.23,2.4,3.123':
    if char == ',':
        total += float(temp_num)
        temp_num = ''
    else:
        temp_num += char

total += float(temp_num) #to catch the last number that has no comma after it

print(total)

答案 19 :(得分:-1)

我认为这是回答问题的最简单方法。它使用split命令,该命令目前未在书中介绍,但非常有用。

s = input('Insert string of decimals, e,g, 1.4,5.55,12.651:')
sList = s.split(',') #create a list of these values
print(sList) #to check if list is correctly created

total = 0 #for creating the variable

for each in sList: 
    total = total + float(each)

print(total)

答案 20 :(得分:-2)

total =0
s = {1.23,2.4,3.123}
for c in s:
    total = total+float(c)
print(total)