How can I suppress the newline after a print statement? [duplicate] - python

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I read that to suppress the newline after a print statement you can put a comma after the text. The example here looks like Python 2. How can it be done in Python 3?
For example:
for item in [1,2,3,4]:
print(item, " ")
What needs to change so that it prints them on the same line?

The question asks: "How can it be done in Python 3?"
Use this construct with Python 3.x:
for item in [1,2,3,4]:
print(item, " ", end="")
This will generate:
1 2 3 4
See this Python doc for more information:
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
--
Aside:
in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,
In [21]: print('this','is', 'a', 'test') # default single space between items
this is a test
In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest
In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

Code for Python 3.6.1
print("This first text and " , end="")
print("second text will be on the same line")
print("Unlike this text which will be on a newline")
Output
>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline

print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:
print "Foo %10s bar" % baz,

Because python 3 print() function allows end="" definition, that satisfies the majority of issues.
In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:
from pprint import PrettyPrinter
class CommaEndingPrettyPrinter(PrettyPrinter):
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
# this is where to tell it what you want instead of the default "\n"
self._stream.write(",\n")
def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
printer = CommaEndingPrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
Now, when I do:
comma_ending_prettyprint(row, stream=outfile)
I get what I wanted (substitute what you want -- Your Mileage May Vary)

There's some information on printing without newline here.
In Python 3.x we can use ‘end=’ in the print function. This tells it to end the string with a character of our choosing rather than ending with a newline. For example:
print("My 1st String", end=","); print ("My 2nd String.")
This results in:
My 1st String, My 2nd String.

Related

Python 2.x.x how to add a comma in print statement of python without preceding space character?

I am new to python and learning,
Code:
name = "Andrew"
print name,","
Output:
Andrew ,
A space character is injected in before the comma, which is undesirable. How may we print the comma immediately after name like Andrew, with no intervening space character?
The default behavior of the print command of Python is to add a space between its arguments.
In Python 2.x.x:
You could use the string concatenation operator + to do this before you print it like:
name = "Andrew"
print name + ","
Output:
Andrew,
However, if you are dealing with Python 3.x.x you could use the argument sep to change the separator from space to empty character like:
print(name, ",", sep="")

Why is there an extra space in between a variable and punctuation in a string? Python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 7 months ago.
There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation().
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
print ("Right... So your name is", name,".")
This is the output it gives.
Right... So your name is Raven .
How do I get rid of the space in between the name and the punctuation?
If you use:
print ("Right... So your name is", name,".")
You will notice that the output is:
Right... So your name is Raven .
Look at is and name (Raven). You can note in the output an space (is Raven), that is because print() have a default argument called sep an by default it's print("Right... So your name is", name,".", sep = ' '). That argument is an string that it's added at the end of each piece of string concatenated with a coma , in the print function.
So if you do print('A','B') it will be A B, because when you concatenate A and B, print will add ' ' (and space) as glue.
You can configure it: print('A','B', sep='glue') would print AglueB!
To solve your problem you can do two options.
Change sep = '' and add an space after is: print ("Right... So your name is ", name,".", sep='')
Or, concatenate using + the last two strings: print ("Right... So your name is", name + ".")
Also there are a lot of another ways like: (I ordered them by worst to best in my subjetive opinion...)
print("Right... So your name is %s." % name).
print("Right... So your name is {}.".format(name)).
print(f"Right... So your name is {name}.")
Link with documentation:
Python Official Documentation
Python 3 Course (Use of sep and ,, +, %s, .format(), f-string and use of string class)
PyFormat (Basic and advanced use of %s, %d, .format(), value conversion, datetime, ).
P.S: This isn't part of the answer, it's just a note.
print (something) don't need the space --> print(something).
Futhemorer sep = ' ' there is also called end = '\n' that determine the end of a print (\n = new line).
P.S 2: Thanks Ouss for the idea of add some documentations links. I've just learnt that you can do print(%(key)s % mydict)!
You can append string with +.
print ("Right... So your name is", name + ".")
Output:
Right... So your name is Raven.
Use the string variable substitution with %s as in:
def nameConfirmation():
name = chooseName()
print ("Right... So your name is %s." % name)
or use the .format() function that is a built-in method for str in:
def nameConfirmation():
name = chooseName()
output = "Right... So your name is {}.".format(name)
print(output)
or you could use the shorter f"" format as in:
def nameConfirmation():
name = chooseName()
print(f"Right... So your name is {name}.")
For more on string manipulation and formatting in Python3, Check the following:
https://www.digitalocean.com/community/tutorials/an-introduction-to-string-functions-in-python-3
https://www.digitalocean.com/community/tutorials/an-introduction-to-working-with-strings-in-python-3
https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
Each argument passed through the print command is automatically separated by a space. I see you're in python 2, and I use python 3, so I'm not sure if this solution will work, but you can try doing this:
print ("Right... So your name is ", name,".",sep='')
This basically (assuming it works in python 2 as well) changes the separation between arguments to no space instead of 1 space.
The comma indicates a continuation on the same line with a space in between (you'll notice there's a space between "is" and "Raven", even though neither string has one in there). If you want to remove the spaces, the usual way to concatenate strings is with a plus
Edit: Plus, not ampersand... stupid me
The reason why does the code produces a extra space is because the default sep looks like this:
sep = ' '
And the seperator seperates the values/input because by default sep contains a space. So that's why even though you did not put a blank space it still does the job for you.
Just in case you don't know what is sep, it is a short form for separator.
There are 3 easy solutions to solve this problem:
\b escape sequence.
'+' string concatanation
sep=''
1st Solution (\b escape sequence):
print ("Right... So your name is", name,"\b.")
2nd Solution ('+' string concatanation):
print ("Right... So your name is", name + ".")
3rd Solution (sep=''):
print ("Right... So your name is ", name,".",sep='')
All of them produces same output:
Right... So your name is Raven.

How to do ghost-like typist in Python

I'm a beginner, how can I do ghost-like typist in console?
EDIT:
I did something like this, just prints a letter per line:
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter)
ghostPrint("Hello world...")
This one, just changes letter in the same line:
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter, end="\r")
ghostPrint("Hello world...")
And this one, prints Hello World... then closes:
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter, end = " ")
ghostPrint("Hello world...")
I am currently using Python 3.5.
In Python 2, a trailing comma after a print statement will suppress the newline (it also adds a space between the arguments to print). So
print var1, var2,
prints the values of var1 and var2 with a space in between, and does not print a trailing newline.
In Python 3, the print function takes two arguments, sep and end. The default values are sep=' ' and end='\n'. Use sep to change what string is used to separate arguments to print, and use end to change what string is printed after everything else.
Use a trailing comma(,) to avoid a newline.
import time
def ghostPrint(sentence):
for letter in sentence:
time.sleep(0.12)
print (letter),
ghostPrint("Hello world...")
In python 3.x using print (letter,end='') will not work I guesses as it print every thing at once.

Remove whitespace in print function [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 7 years ago.
I have this code
print "/*!",your_name.upper(),"*/";
where your_name is the data the user inputs.
How can I edit the code above to tell the system to remove any whitespace?
UPDATE:
If i print the code, i'll get
/*! your_name */
I want to remove the whitspaces between /*! your_name */
The spaces are inserted by the print statement when you pass in multiple expressions separated by commas. Don't use the commas, but build one string, so you pass in just the one expression:
print "/*!" + your_name.upper() + "*/"
or use string formatting with str.format():
print "/*!{0}*/".format(your_name.upper())
or the older string formatting operation:
print "/*!%s*/" % your_name.upper()
Or use the print() function, setting the separator to an empty string:
from __future__ import print_function
print("/*!", your_name.upper(), "*/", sep='')
The white spaces are inserted by print when you use multiple expressions separated by commas.
Instead of using commas, try :
print "/*!" + your_name.upper() + "*/"

Print without a newline between two strings [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 9 years ago.
I want to print some text beside another text that has been printed before in python
for example
print("Hello")
a="This is a test"
print(a)
What I mean is to print like this "HelloThis is a test" not in next line I know I shoud use print("Hello",a) but I wanted to use seprated print commands!!!!
Use end='' in the first print call:
print("Hello", end='')
a = "This is a test"
print(a)
#HelloThis is a test
Help on print:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
If you are using python 2.7 (python tag on question) you can place a comma after the print to not return a new line.
print("hello"),
print("world")
Will print "helloworld" all one one line.
So in your case it will be:
print("Hello"),
print(a)
Or if your using python 3 (python3.x tag on question) use:
print("hello", end='')
print('world')
So in your case it will be:
print("Hello", end='')
print(a)

Categories