Deleting carriage returns caused by line reading

前端 未结 3 1665
一向
一向 2021-02-18 17:41

I have a list:

Cat
Dog
Monkey
Pig

I have a script:

import sys
input_file = open(\'list.txt\', \'r\')
for line in input_file:
           


        
3条回答
  •  臣服心动
    2021-02-18 18:08

    You can use .rstrip() to remove newlines from the right-hand side of a string:

    line.rstrip('\n')
    

    or you can tell it to remove all whitespace (including spaces, tabs and carriage returns):

    line.rstrip()
    

    It is a more specific version of the .strip() method which removes whitespace or specific characters from both sides of the string.

    For your specific case, you could stick with a simple .strip() but for the general case where you want to remove only the newline, I'd stick with `.rstrip('\n').

    I'd use a different method to write your strings though:

    with open('list.txt') as input_file:
        print ','.join(['"{}"'.format(line.rstrip('\n')) for line in input_file])
    

    By using ','.join() you avoid the last comma, and using the str.format() method is easier on the eyes than a lot of string concatenation (not to mention faster).

提交回复
热议问题