Deleting carriage returns caused by line reading

前端 未结 3 1646
一向
一向 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:05

    First of all, in order to make it all appear on one line you should get rind of the '\n'. I find line.rstrip('\n') to work nicely.

    In order to get rid of the ',' at the end I would put all of the words in a list adding the quotation marks. Then using join(), join all of the words in the list with ","

    temp = []
    for line in file:
        i = line.rstrip('\n')
        word = '"'+i+'"'
        temp.append(word)
    print ",".join(temp)
    

    That should get the desired output

提交回复
热议问题