加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python – 使用空格格式化file.write字符串

发布时间:2020-12-20 11:45:22 所属栏目:Python 来源:网络整理
导读:我有一个程序,并从我使用另一个 python代码创建的.txt文件中读取.我在完成这个问题时遇到了麻烦. 它需要读取.txt并吐出该文件中的数字及其总和.这是我到目前为止所得到的: def main(): total = 0 myfile = open('numbers.txt','r') for line in myfile: amo
我有一个程序,并从我使用另一个 python代码创建的.txt文件中读取.我在完成这个问题时遇到了麻烦.

它需要读取.txt并吐出该文件中的数字及其总和.这是我到目前为止所得到的:

def main():
    total = 0
    myfile = open('numbers.txt','r')
    for line in myfile:
        amount = float(line)
        total += amount
    print('End of file')
    print('Numbers in file add up to ',format(total,',.1f'),end='')
    myfile.close()

main()

我收到错误消息:

ValueError: could not convert string to float: '11 13 11 7 7'

解决方法

现在,试试这个:

def main():
    total = 0
    with open('numbers.txt','r') as myfile:
        for line in myfile:
            for i in line.split():
                amount = float(i)
                total += amount
        print(line.strip(),'End of file')
        print('Numbers in file add up to ',end='')
        print()

main()

因为线是一条线,那就是’11 13 11 7 7′.

所以float()不能将这样的字符串转换为float.这些代码使用split()将该字符串拆分为[’11’,’13’,’11’,’7′,’7’等列表.然后用它来提取它.

现在,float()可以将’11’,’13’等转换为float.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读