删除换行符不起作用

时间:2014-03-06 16:51:16

标签: python

我试图从函数中创建的列表中删除\n。我删除它的代码似乎没有用。我没有得到错误??

CODE

#!/usr/bin/python

"""
Description:

Basic Domain bruteforcer

Usage:
  your_script.py (-f <file>) (-d <domain>) [-t 10] [-v]
  your_script.py -h | --help

Arguments:
  -f --file File to read potential Sub-domains from. (Required)
  -d --domain Domain to bruteforce. (Required)
Options:
  -h --help     Show this screen.
  -p --proxy    Proxy address and port. [default: http://127.0.0.1:8080] (Optional)
  -t --thread   Thread count. (Optional)
  -v --verbose  Turn debug on. (Optional)
"""
from docopt import docopt


def fread(dwords, *args):
        flist = open(dwords).readlines()
        #print current list
        print flist
        nlist = flist
        for i in nlist:
          i.rstrip('\n')
          return nlist

if __name__ == "__main__":
        arguments = docopt(__doc__, version='0.1a')
        # print new list with removed \n
        print fread(arguments['--file'])

1 个答案:

答案 0 :(得分:8)

字符串不可变,i.rstrip('\n') 返回一个新字符串。

使用列表理解:

def fread(dwords):
    flist = open(dwords).readlines()
    return [s.rstrip('\n') for s in flist]

或者,因为您正在将整个文件读入内存,str.splitlines()

def fread(dwords):
    return open(dwords).read().splitlines()