【问题标题】:File writing in Python 3.3用 Python 3.3 编写文件
【发布时间】:2018-03-02 10:17:56
【问题描述】:

谁能给我关于写文件的建议。这是在 python 3.3 中。此错误消息不断弹出。

Traceback(最近一次调用最后一次):第 28 行,在 file.write(name_1,"and",name_2,"have a",loveness_2,"percent chance of fall in love") 类型错误:write() 恰好1 个参数(给定 6 个)

我的代码是这样的:

  if vowels_1 > vowels_2:
      loveness = vowels_2/vowels_1
      loveness_2 = loveness * 100
      print("It is ",loveness_2,"% possible of you falling in love")
      print("*********************************************")
      file.write("*********************************************")
      file.write(name_1,"and",name_2,"have a",loveness_2,"percent chance of 
      falling in love")

【问题讨论】:

标签: python python-3.3


【解决方案1】:

file.write与print不一样;正如错误所说,它只需要一个参数。您需要在将字符串传递给该调用之前编写字符串。

一种方法是使用字符串格式化:

line = "{} and {} have a {} percent chance of falling in love".format(name_1, name_2, loveness_2)
file.write(line)

【讨论】:

    【解决方案2】:

    逗号分隔参数,所以解释器认为你在​​这里给出了一堆参数。如果要进行字符串连接,请使用“+”。

    print('a' + 'b')
    >>> 'ab'
    

    一种更 Pythonic 的方式是使用 .format()

    print('{} some text {}'.format('foo', 'bar')
    >>>'foo some text bar'
    

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 2014-02-05
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多