How to remove whitespace from the output of the following script? - python

for i in range(1, 4):
print i,
Output is 1 2 3, but I want the output like 123, i.e without spaces,
so how to do it?

As a technical note, while you should definitely not print this way if what you want is one string, it's doable with Python 3's print:
from __future__ import print_function
for i in range(1, 4):
print(i, end='')
See the other answers for how to do this building a string instead.

In python2, you have to use sys.stdout.write() to avoid the spaces inserted by the print command:
import sys
for i in range(1,4):
sys.stdout.write(str(i))
sys.stdout.flush()
Edit: as noted by GPhilo, you can also use python3's print function that has the option of avoiding separators, after importing it from __future__.

Related

how to eliminate new line in python

I am new to python and I am having problem over the following syntax:
for x in range(0, 10):
print(x, ' ', end="")
I saw the syntax on a tutorial, however when I try it, it is giving me error. The goal I am trying to reach is printing 0 to 9 while eliminating new line. In other words, print 0 to 9 in a single line. Can you tell me what's wrong with the syntax if there is any?
To print in Python 2.7 without the line break you just need to add an extra comma to the end. It will also add a space between the numbers.
for x in range(0, 10):
print x,
Are you using python 2? Because print() with end keyword argument is a Python 3 command.
The print function with keyword end of Python 3 can be imported into Python 2 by
importing from __future__ at the very beginning of the script:
from __future__ import print_function
However, Python 2's print statement allows a syntax form without parentheses. This syntax will break with this import.

Delete last printed character python

I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)

Overwrite previous output on same line

I want the output of my code to overwrite the previous output on the same line.
I have read the previous answers to a similar question and have read that I can do this using a ',' and a '\r', but this doesn't seem to work for me. I tried:
for i in range(length):
print 'Minutes:',minute,'of {0}'.format(length),'\r',
minute+=1
time.sleep(1)
But it doesn't print anything other than the last line of the loop. I've tried other arrangements,but nothing yet has worked. Could someone let me know what I'm doing wrong?
Thanks.
If You are doing this in Linux, You can simply use ASCII escape sequence to move cursor up one line (\033[1A). Of course, You will still use \r to move to the beginning of the line. You could use something like this:
for i in range(length):
print('Minutes: ' + minutes + '\033[1A\r')
minutes += 1
sleep(1)
You need sys.stderr for fast output on a screen:
import sys,time
length,minute = 10,0
for i in range(length):
sys.stderr.write('Minutes:{} of {}\r'.format(minute,length))
minute+=1
time.sleep(1)
Don't forget to add sys.stderr.write('\n') at the end of your loop to avoid printing into the same line.
The easiest way I can think of doing this is, if you know how many lines your shell is, then you can just
print "\n" * (number_of_lines - 1)
then
print 'Minutes:',minute,'of {0}'.format(length)
So together,
for i in range(length):
print "\n" * (number_of_lines - 1)
print 'Minutes:',minute,'of {0}'.format(length)
minute += 1
time.sleep(1)
General Tips
You use commas and str.format() in the same print statement, instead just use str.format() for all of it. e.g print 'Minutes: {0}, of {1}'.format(minute, length).
You used minute as your counter even though it appears you are counting by seconds. For clarity you may want to rename that variable second.
Note
sys.stderr is the better way to do this. Please look at rth's answer
If you are using Python3, you can use a code like this:
import time
minute, length = 1, 100
for i in range(length):
print ('Minutes: {0} of {1}\r'.format(minute, length), end = "")
minute+=1
time.sleep(1)
However if you are using Python2, you can import print_function from __future__ module like this example:
from __future__ import print_function
import time
minute, length = 1, 100
for i in range(length):
print("Minutes: {0} of {1}\r".format(minute, length), end = "")
minute+=1
time.sleep(1)
PS: I have a strange issue when running the last code from my terminal using Python2.7.10. The script work but there is not any output.
However within Python 2.7.10 interpreter the code works fine.
Test both solutions and leave your feedbacks if you encounter any problems within Python2.
EDIT:
I think the better solution to avoid the strange issue that i encounter, and i don't know the cause, is using the ASCII escape as #Fejs said in his answer.
Your code will be something like this:
import time
minute, length = 1, 100
for i in range(length):
print "Minutes: {0} of {1} {2}".format(minute, length, '\033[1A\r')
minute+=1
time.sleep(1)
Try flushing the output before each sleep.
minute+=1
sys.stdout.flush()
time.sleep(1)

Avoid spurious space in print [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 10 years ago.
I did not expect this, but:
print "AAAA",
print "BBBB"
Will output:
AAAA BBBB
With an extra space in the middle. This is actually documented.
How can I avoid that supurious space? The documentation says:
In some cases it may be functional to write an empty string to standard output for this reason.
But I do not know how to do that.
Three options:
Don't use two print statements, but concatenate the values:
print "AAAA" + "BBBB"
Use sys.stdout.write() to write your statements directly, not using the print statement
import sys
sys.stdout.write("AAAA")
sys.stdout.write("BBBB\n")
Use the forward-compatible new print() function:
from __future__ import print_function
print("AAAA", end='')
print("BBBB")
Get used to use print() function instead of the statement. It's more flexible.
from __future__ import print_function
print('foo', end='')
print('bar')

Printing directly from read() in Python adds an extra newline

I've got a Python script that prints out a file to the shell:
print open(lPath).read()
If I pass in the path to a file with the following contents (no brackets, they're just here so newlines are visible):
> One
> Two
>
I get the following output:
> One
> Two
>
>
Where's that extra newline coming from? I'm running the script with bash on an Ubuntu system.
Use
print open(lPath).read(), # notice the comma at the end.
print adds a newline. If you end the print statement with a comma, it'll add a space instead.
You can use
import sys
sys.stdout.write(open(lPath).read())
If you don't need any of the special features of print.
If you switch to Python 3, or use from __future__ import print_function on Python 2.6+, you can use the end argument to stop the print function from adding a newline.
print(open(lPath).read(), end='')
Maybe you should write:
print open(lPath).read(),
(notice trailing comma at the end).
This will prevent print from placing a new-line at the end of its output.

Categories

Resources