j.doe j.doe - 1 year ago 75
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:

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


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 Source

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')



>>> print('a')

So you want to remove that:

>>> with open('test_file.txt') as f:
...     for line in f:
...         print(line.rstrip('\n'), end='<something>')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download