j.doe j.doe - 2 months ago 8
Python Question

Is there a way to avoid a new line while using `end=`

I've just started using python and I'm creating a simple program that will ask whoever the user is a question and then from the text file I will extract a specific line and print that line and along with the line - at the end I will add their answer. here's the code.

question = input("do you want to print the line")
if "yes" in question:
print(open("tp.txt").readlines()[:10][-1],end=question)


The issue is that
,end=question)
puts the users answer on a new line. I know that
end=
is the same as
\n
. So I'm just wondering is there a way or an alternative to stop 'end=' from automatically creating a new line?

print(open("tp.txt").readlines()[:10][-1],


is the way I open and read a specific line from the file
since its a 'nice' shortcut to do than rather do
with open (filename.txt,'r') as f:

Answer

The problem is that the lines returned by readlines() contain the ending newline:

$ echo 'a
> b
> c
> ' > test_file.txt
$ python3
Python 3.5.2 (default, Jul  5 2016, 12:43:10) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('test_file.txt') as f:
...     print(f.readlines())
... 
['a\n', 'b\n', 'c\n', '\n']

See the \n? Note the difference bewteen:

>>> print('a\n')
a

>>>

And:

>>> print('a')
a
>>>

So you want to remove that:

>>> with open('test_file.txt') as f:
...     for line in f:
...         print(line.rstrip('\n'), end='<something>')
... 
a<something>b<something>c<something><something>>>>