Shreyas Shridharan
Shreyas Shridharan

Reputation: 291

Why is a newline being added at the end of my strings?

I have a small question. I noticed that, for some reason, when I use the + symbol when joining two variables, Python automatically uses a newline.

for i in range(o):
    a = Before.readline()
    b = After.readline()
    if a == b:
        lines.append(" \n")
    else:
        plus = a + b
        lines.append(a + b)

Final.writelines(lines)

This would result in a list with values as such (Notice the 'B\nC\n')

[' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n',
 ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n',
 'B\nC\n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n', ' \n']

Assuming that I have initialized the files Before, After, and Final correctly, what should I do to remove these newlines and just add a space? I would prefer to do this without using many libraries.

EDIT : I do know about the .strip() method. It is indeed very helpful, to remove the new lines. However, I seem to have phrased my question a little wrong. I was also wondering about how to add the new lines, as a + ' ' + b doesn't really seem to work. How would I do this?

DOUBLE EDIT : I'm stupid. I put the wrong variable in the appending area. Nevermind, and thanks anyways!

Upvotes: 2

Views: 1323

Answers (1)

LTClipp
LTClipp

Reputation: 534

The Before.readline() and After.readline() are including the newlines in the file you are reading. To remove the trailing newlines and whitespaces, you can:

Before.readline().strip()

Then if you want to add newlines in your a+b line, you will need to format it explicitly how you want, in any way you want. For example:

  • a + ' ' + b
  • "{} {}".format(a,b)
  • a + b + "\n"
  • etc

You could also only perform .strip() on a when you are adding it to the list. So many possibilities!

Upvotes: 5

Related Questions