0

I'm using this code:

konto_fail = open("konto.txt")
for line in konto_fail:
    if float(line) > 0:
        print (line)

If I run the program it prints out the necessary lines, but there is a empty line in between them that I don't want. How do I fix this?

karel
  • 5,489
  • 46
  • 45
  • 50
reimotaavi
  • 57
  • 6
  • 2
    Possible duplicate of [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) – slhck Mar 01 '19 at 13:39

2 Answers2

0

That's because the last char of line is \n aka a newline.

To prevent that from happening, do a

print(line, end='')

The default end is \n so by default, you add two new lines (one in the string, and one at the end of the print).


That means that the solution I provided above is equivalent to

print(line[:-1])

You can also remove all newlines by doing

print(line.replace('\n', ''))

Remove all trailing whitespaces (including newlines)

print(line.strip())

Remove all trailing whitespaces (including newlines) at the end

print(line.rstrip())

Remove all trailing whitespaces (including newlines) at the beginning

print(line.lstrip())
Benoît P
  • 3,179
  • 13
  • 31
0

Python syntax for printing is different than other languages. Printing the next output in the next line is default. So, to change it, put an end=''(if not specified, end is \n) as the last attribute of the function print()

konto_fail = open("konto.txt")
for line in konto_fail:
    if float(line) > 0:
        print (line, end = '')
Eshita Shukla
  • 791
  • 1
  • 8
  • 30