【问题标题】:converting a tuple consisting of floats and text to one single string将包含浮点数和文本的元组转换为单个字符串
【发布时间】:2017-07-06 11:04:12
【问题描述】:

我正在尝试将包含 2 个浮点数和 3 个文本部分的元组转换为一个字符串,以便我可以在 file.write() 中使用它,因为它不接受元组。

testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()

每当我尝试运行程序时,它都会给我这个

    test.write(testr)
TypeError: must be str, not tuple

【问题讨论】:

    标签: python file text


    【解决方案1】:

    使用format:

    testr = 'you went {} mph and stopped in {} meters'.format(speed, stop)
    

    【讨论】:

      【解决方案2】:

      与其他答案不同,这将采用您提出的元组:

      testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
      test = open('testresults.txt' ,'w')
      test.write(" ".join(str(i)for i in testr))
      test.close()
      

      由于只有第三行与您的代码不同,因此解释如下:

      第一个str(i)for i in testr:

      内联for-loop 在 python 中称为list comprhension。它只是遍历您的 testr 元组,一一返回值。 str(i) 是一种类型转换,它尝试将i 转换为字符串。这是必要的,因为在您的元组中,一些条目是 String-type,而一些变量是某种类型的数字,可能是 Float 或 Integer。请参阅str()、float() 和int() 进一步阅读。

      然后" ".join(...):

      这是一个字符串类型的函数,它接受一个字符串列表或元组,并且正如名称所暗示的那样,将它连接在一起,由它作用的子字符串分隔,点前面的部分(" ")。这对我来说总是觉得有点奇怪,或者可能是由内而外,但它仍然是一个非常有用的功能!

      我希望这会有所帮助!

      【讨论】:

      • 谢谢它成功了!你能解释一下这是如何工作的吗?所以我可以用它来以其他方式工作,或者我做的其他项目。
      【解决方案3】:

      将其转换为String

      test.write(str(testr))
      

      【讨论】:

        【解决方案4】:

        谢天谢地,python 3.6 让我们可以轻松阅读:

        testr = f'you went {speed} mph and stopped in {stop} metres'
        test = open('testresults.txt' ,'w')
        test.write(testr)
        test.close()
        

        否则,使用另一个答案中提到的string.format(*args) 可以实现相同的目标。

        【讨论】:

        • python2 怎么样?
        猜你喜欢
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-25
        • 2018-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多