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?
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())
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 = '')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.