What is the comma (,) in the middle of print used for? - python

I was wondering what the comma in the middle of print is used for?
This code:
print('No. of lower case letters : ', d['lower'])

A bit of history
Since Python 3, there is actually no print statement. Print is a function just like any other (In the now obsolete Python 2, print was indeed actually a statement).
A special case in Python 2 is that you could indeed have a comma at the end, such like
print "my string",
This would print the string with a space rather than a line feed as the terminator, allowing multiple print statements to contribute to one line. But forget about all this now, Python 2 is long gone (well, since January 2020).
Now to your question.
All functions in Python accept a number of arguments separated by a comma. The print function is no different. The print function takes any number of positional arguments, as well as a number of well-known named arguments, e.g.
print(a,b,c, file=f)
will send the positional arguments a, b and c and the keyword argument file. The print function will concatenate all positional arguments (separated by space) when printing them (optionally to the file specified by the file argument, otherwise to standard output).

The comma let's you add multiple arguments to the print statement. It basically lets you print them in succession, separated by a space.
Example:
print('hi', 'hello', 'greetings')
#hi hello greetings

The comma will let you print multiple strings in one calling of the print function. By default, each string will be separated by a space.
These are the arguments for the print function:
print(*objects, sep=' ', end='\n', file=sys.stdout)
You can change the sep argument to something else.

Related

Why does '\n' output an extra blank line in Python3

In python3 print('\n') will generate an extra blank line. Could someone make a brief explanation about this?
Thanks in advance.
In the documentation for print it is stated that:
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.
The default value for end is '\n', so Python first prints the supplied '\n' and then end which equals '\n' too; that's why you see two blank lines.
Change the default value if you don't want that:
print('\n', end='')
Note that this also applies to Python 2.x's print statement, it also writes '\n' at the end. You can change the behavior there by appending a comma character.

PYTHON: Use of this ',' in python? [duplicate]

I am learning python(2.7) on my own.
I have learned that we can use the following ways to put strings and variables together in printing:
x = "Hello"
y = "World"
By using commas:
print "I am printing" , x, y # I know that using comma gives automatic space
By using concatenation :
print "I am printing" + " " + x + " " + y
By using string formatters
print "I am printing %s %s" % (x, y)
In this case all three print the same:
I am printing Hello World
What is the difference between the three and are there any particular instances where one is preferred over the other?
To answer the general question first, you would use printing in general to output information in your scripts to the screen when you're writing code to ensure that you're getting what you expect.
As your code becomes more sophisticated, you may find that logging would be better than printing, but that's information for another answer.
There is a big difference between printing and the return values' representations that are echoed in an interactive session with the Python interpreter. Printing should print to your standard output. The echoed representation of the expression's return value (that show up in your Python shell if not None) will be silent when running the equivalent code in scripts.
1. Printing
In Python 2, we had print statements. In Python 3, we get a print function, which we can also use in Python 2.
Print Statements with Commas (Python 2)
The print statement with commas separating items, uses a space to separate them. A trailing comma will cause another space to be appended. No trailing comma will append a newline character to be appended to your printed item.
You could put each item on a separate print statement and use a comma after each and they would print the same, on the same line.
For example (this would only work in a script, in an interactive shell, you'd get a new prompt after every line):
x = "Hello"
y = "World"
print "I am printing",
print x,
print y
Would output:
I am printing Hello World
Print Function
With the built-in print function from Python 3, also available in Python 2.6 and 2.7 with this import:
from __future__ import print_function
you can declare a separator and an end, which gives us a lot more flexibility:
>>> print('hello', 'world', sep='-', end='\n****\n')
hello-world
****
>>>
The defaults are ' ' for sep and '\n' for end:
>>> print('hello', 'world')
hello world
>>>
2. String Concatenation
Concatenation creates each string in memory, and then combines them together at their ends in a new string (so this may not be very memory friendly), and then prints them to your output at the same time. This is good when you need to join strings, likely constructed elsewhere, together.
print('hello' + '-' + 'world')
will print
hello-world
Be careful before you attempt to join in this manner literals of other types to strings, to convert the literals to strings first.
print('here is a number: ' + str(2))
prints
here is a number: 2
If you attempt to concatenate the integer without coercing it to a string first:
>>> print('here is a number: ' + 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
This should demonstrate that you should only ever attempt to concatenate variables that are known to be strings. The new way of formatting demonstrated next handles this issue for you.
3. String Interpolation
The formatting you're demonstrating is the old style of string interpolation, borrowed from C. It takes the old string and one time creates a new one. What it does is fairly straightforward. You should use this when you may seem likely to building up a fairly large template (at 3+ lines and 3+ variables, you definitely should be doing it this way).
The new way of doing that would be to do this (using the index of the arguments):
print('I am printing {0} and {1}'.format(x, y))
or in python 2.7 or 3 (using the implied index):
print('I am printing {} and {}'.format(x, y))
or with named arguments (this is semantically easy to read, but the code doesn't look very DRY (i.e. Don't Repeat Yourself))
print('I am printing {x} and {y}'.format(x=x, y=y))
The biggest benefit of this over % style formatting (not demonstrated here) is that it lets you combine positional and keyword arguments
print('I am printing {0} and {y}'.format(x, y=y))
New in Python 3.6, format literals
Python 3.6 will have format literals, with a more elegant syntax (less redundancy). The simple syntax is something like:
print(f'I am printing {x} and {y}')
The format literals can actually execute code in-place:
>>> print(f'I am printing {"hello".capitalize()} and {"Wo" + "rld"}')
I am printing Hello and World
you should build list and use join with delimiter
for example
",".join(list_name)

Python printing issue with space

Hello I am currently working on something and I am trying to print output as such in python
hello=10
but my code below is printing it as such
hello= 10
10 is an int i have tried these codes but none work
print "hello=",10
print "hello=",str(10)
print "hello=",str(10).strip()
i would appreciate the help thank you
Simply concatenate the strings:
print "hello="+str(10)
Use str.format,
print("hello={}".format(10))
PS: The print statement has been replaced with a print() function since Python 3.0.
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Refer to Print Is A Function for the detailed descriptions.
If you use print with multiple arguments, separated by ,, a single space ' ' is inserted as a separator in between each of those.
When using Python 3's print function, you can specify the sep parameter; default is ' '.
>>> from __future__ import print_function # when in Python 2
>>> print("hello=", 10)
hello= 10
>>> print("hello=", 10, sep="")
hello=10
>>> print("hello=", 10, sep="###")
hello=###10
For Python 2's print statement, there is to the best of my knowledge no such option.
You may also consider using the Python 3 compatible print() function:
This function can be used after a __future__ directive:
from __future__ import print_function
print("hello=", 10, sep='')
Output:
hello=10
The print() function as a sep keyword argument which allows you to replace the space separator by an empty string.
Here is the online help:
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
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.
flush: whether to forcibly flush the stream.
The call "print" will place a space for a comma.
Yes, Python provides many ways to print the strings as above mentioned, I still would like to construct the output with C or Java style format:
print "hello=%d" % 10

Why print command gives a new line even though there is no data to print

Just typing print only gives newline in python. Typing print without the brackets in 3.x will also gives a newline. Why?
Because the documentation says so
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.
Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
Changed in version 3.3: Added the flush keyword argument.
Note that end is defaulted to '\n' which is a new line.
In Python 3, print is now a function. It will print a new line character at the end of your statement.
If you don't specify an "end" it will by default use a new line character.
You can prevent this by doing something such as:
print("hello world", end="")
Because the default parameter in print is \n for the end,
though if you pass parameter for print end variable as \t or space , then you can see the same !
But it works 2.7 and above!
It is interesting how languages differ in this.
print in the Korn shell (ksh) has the same behaviour as python, i.e. it adds a newline. Bash does not have a print, relying on echo instead, which also adds a newline (which, like python, can be suppressed).
print in Perl does not, and caused so much inconvenience that another version, called say, was added which does add a newline.
Ruby and PHP are like Perl in that print also does not add a newline. This of course is less of an issue when embedded in HTML.
If you look at other languages, for example here you will find opinion divided as to whether a newline should be added or not. The removal of the newline in Python is discussed in PEP259.

Python 2.7.9 Print statement with list strange output

Why whole argument in print function along with paranthesis is printed when only the string should have been
This is Python 2.7.9
import os
alist = [ 'A' ,'B']
print('Hello there')
print('The first item is ',alist[0])
print('Good Evening')
root#justin:/python# python hello.py
Hello there
('The first item is ', 'A')
Good Evening
In python 2 print isn't a function it's a statement. When you write
print('The first item is ',alist[0])
it's actually means "print me a tuple of 2 elements: 'The first item is ' and alist[0]"
it's equivalent to
a = ('The first item is ',alist[0])
print a
if you want to print only strings you should remove the parentheses like that:
print 'The first item is ',alist[0]
EDIT:
As guys in comments tell, you can also add
from __future__ import print_statement
This will make print a function like in python 3 and your examples will work as you expected without any changes.
But I think it's useful to understand what is going on in both cases.
Earlier answers have explained that
print('The first item is ', alist[0])
in Python 2 is equivalent to
print ('The first item is ', alist[0])
so it prints a tuple of two items. That's because print is a statement in Python 2, not a function, so parentheses following print are not interpreted as indicating a function call.
In Python, an expression consisting of several items separated by commas creates a tuple. In some cases, parentheses are required to group the tuple into a single unit; and the print statement is one of those cases, otherwise each item in the comma-separated sequence is treated as a separate argument to the print statement.
The standard string representation of a tuple prints the enclosing parentheses and the repr of each tuple item. Thus any string items in the tuple are printed with their quote marks, and various escape sequences are used to represent non-ASCII characters.
If you wish to use the print() syntax in latter versions of Python 2 in order to make your code compatible with Python 3 then you should put
from __future__ import print_function
as the first executable statement in your script. That will mask the print statement and allow the print name to refer to the print function instead. Here's a short demo, running on Python 2.6.6. First, without the import:
print('one', 'two\n', 'three')
output
('one', 'two\n', 'three')
And with the import:
from __future__ import print_function
print('one', 'two\n', 'three')
output
one two
three
FWIW, you might as well do
from __future__ import print_function, division
So you get Python 3-style behaviour of the / division operator too.
Remember You're using python 2.7.x in python 2, print is a statement, not a function.
You might ask why
print('Good Evening')
doesn't print
('Good Evening')
You're passing only 1 string argument hence the print statement understands that the string needs to be printed and not the parentheses.
when you do
print ('The first item is ',alist[0])
The whole output is printed thinking that there are different parts of the string having , as the delimiter, hence the output is
('The first item is ', 'A')
Remove parentheses while dealing with python 2 because it is not a function oriented version

Categories