How to remove more than one space when reading text file

后端 未结 2 1734
臣服心动
臣服心动 2021-01-19 16:48

Problem: I cannot seem to parse the information in a text file because python reads it as a full string not individual separate strings. The spaces between each variable is

相关标签:
2条回答
  • 2021-01-19 16:58

    You can instruct csv.reader to use space as delimiter and skip all the extra space:

    reader = csv.reader(f, delimiter=" ", skipinitialspace=True)
    

    For detailed information about available parameters check Python docs:

    Dialect.delimiter A one-character string used to separate fields. It defaults to ','. Dialect.skipinitialspace When True, whitespace immediately following the delimiter is ignored. The default is False.

    0 讨论(0)
  • 2021-01-19 17:10

    You can simply declare the delimiter to be a space, and ask csv to skip initial spaces after a delimiter. That way, your separator is in fact the regular expression ' +', that is one or more spaces.

    rd = csv.reader(fd, delimiter=' ', skipinitialspace=True)
    for row in rd:
        print row
    
    ['MOR125-1', 'MOR129-1', '0.587']
    ['MOR125-1', 'MOR129-3', '0.598']
    ['MOR129-1', 'MOR129-3', '0.115']
    
    0 讨论(0)
提交回复
热议问题