【问题标题】:Can't figure out where function is going wrong无法弄清楚功能哪里出错了
【发布时间】:2015-11-02 21:44:48
【问题描述】:

我有一个文本文件 IDlistfix,其中包含一个 youtube 视频 ID 列表。我正在尝试创建一个新的文本文件newlist.txt,它是第一个视频中的 ID,它们周围有撇号,ID 之间有一个逗号。这就是我为实现此目的而编写的:

n = open('IDlistfix','r+')
j = open('newlist.txt','w')
line = n.readline()

def listify(rd):
    return '\'' + rd + '\','

for line in n:
    j.write(listify(line))

这给了我','rUfg2SLliTQ 的输出,我希望输出为'rUfg2SLliTQ',。我的函数哪里出错了?

【问题讨论】:

  • rd.strip() 将去掉换行符。

标签: python python-2.7


【解决方案1】:

你只需要去掉换行符:

j.write(listify(line.strip())) # Notice the call of the .strip() method on the String

【讨论】:

    【解决方案2】:

    尝试删除尾随空格并返回格式化字符串:

    n = open('IDlistfix','r+')
    j = open('newlist.txt','w')
    line = n.readline()
    
    def listify(rd):
        # remove trailing whitespace
        rd = rd.rstrip()
        # return a formatted string
        # this is generally preferable to '+'
        return "'{0}',".format(rd)
    
    for line in n:
        j.write(listify(line))
    

    【讨论】:

      【解决方案3】:

      问题一定出在,

      `return '\'' + rd + '\`','
      

      因为 rd 以 '/n' 结尾。 从rd中删除'/n'应该没问题

      【讨论】:

        【解决方案4】:

        换行有问题。

        变化:

            for line in n:
                j.write(listify(line.replace('\n','')))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-10
          • 2021-06-27
          • 2022-12-02
          • 1970-01-01
          • 2013-02-23
          • 1970-01-01
          • 1970-01-01
          • 2016-07-17
          相关资源
          最近更新 更多