Jon Harper
Jon Harper

Reputation: 105

How to remove extra space from end of the line before newline in python?

I'm quite new to python. I have a program which reads an input file with different characters and then writes all unique characters from that file into an output file with a single space between each of them. The problem is that after the last character there is one extra space (before the newline). How can I remove it?

My code:

import sys
inputName = sys.argv[1]
outputName = sys.argv[2]

infile = open(inputName,"r",encoding="utf-8")
outfile = open(outputName,"w",encoding="utf-8")
result = []
for line in infile:

   for c in line:
       if c not in result:
           result.append(c)
           outfile.write(c.strip())

          if(c == ' '):
             pass
          else:
             outfile.write(' ')

outfile.write('\n')

Upvotes: 2

Views: 178

Answers (1)

David Z
David Z

Reputation: 131760

With the line outfile.write(' '), you write a space after each character (unless the character is a space). So you'll have to avoid writing the last space. Now, you can't tell whether any given character is the last one until you're done reading, so it's not like you can just put in an if statement to test that, but there are a few ways to get around that:

  • Write the space before the character c instead of after it. That way the space you have to skip is the one before the first character, and that you definitely can identify with an if statement and a boolean variable. If you do this, make sure to check that you get the right result if the first or second c is itself a space.
  • Alternatively, you can avoid writing anything until the very end. Just save up all the characters you see - you already do this in the list result - and write them all in one go. You can use

    ' '.join(strings)
    

    to join together a list of strings (in this case, your characters) with spaces between them, and this will automatically omit a trailing space.

Upvotes: 4

Related Questions