【问题标题】:Stripping Unwanted Characters When Writing To A File写入文件时去除不需要的字符
【发布时间】:2016-05-19 01:55:26
【问题描述】:

我在删除 Python 中不需要的字符时遇到了一些问题。 以下代码是从文件中获取的(尽管文件中不包含 \rn\n[]' 字符。)

我想去掉上面列出的所有不必要的字符,这样我就只有数字和文本,然后将它们写入另一个文件。我尝试了很多方法,例如 line.strip,但都没有奏效。

这是我现在写入文件的方式;

product = str(product)
f.write(product)

这是结果

['34512340', 'Plain Brackets', '0.5\r\n']

如果有人可以简单地解释我需要添加什么来删除不必要的字符,我将非常感激。谢谢

【问题讨论】:

    标签: python text strip


    【解决方案1】:
    #list of lines
    lines = ['34512340', '0.5\r\n', 'Plain Brackets'];
    
    #looping through the whole list
    for i in range(len(lines)):
    
        #stripping unwanted characters \n and \r from each line
        lines[i] = lines[i].rstrip('\n').rstrip('\r')
    
        #printing the line without the unwanted characters
        print lines[i]
    

    输出:

    34512340
    0.5
    Plain Brackets
    

    【讨论】:

      【解决方案2】:

      这是一个例子:

      elements = ['34512340', '0.5\r\n', 'Plain Brackets'];
      
      number_of_elements = len(elements);
      
      for i in xrange(0, number_of_elements):
          elements[i] = elements[i].rstrip('\r\n');  # instead of specific symbols, you can also create a list to filter here
          print elements[i];
      

      【讨论】:

      • ; 在这里没有任何用途,而且非常不符合 Python 风格。
      • 对不起,我不明白这个。 @UrsaMajor 有没有更简单的方法来做到这一点?
      • 我的答案和Dot_Py的差不多。
      【解决方案3】:

      只是为了一些变化:

      list(map(lambda x:str(x).rstrip('\r\n'),['34512340', 'Plain Brackets', '0.5\r\n']))
      

      在将逻辑应用于列表中的所有项目时,我真的很喜欢使用内置函数映射。只需制作一条线,而不是循环播放。性能方面不确定它是如何叠加的

      Map function documentation

      Map 将一个函数作为一个参数,然后将一个列表或可迭代类型作为第二个参数,并将该函数应用于列表中的所有项目。我传递了一个 lambda 函数声明,只是为了让它更简洁。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-12
        • 2011-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多