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)
Related
I am using ipython notebook in ubantu version 16.04 and I run this code,
word = 'Rushiraj'
length = 0
for char in 'rushiraj':
length = length + 1
print('There are', length,'character')
I get this output:
('There are', 8, 'character')
What is the reason for this single quotes and round braces in output ?It should not be there !
The output you are seeing is due to the fact that you are using Python 2, but you're using the print syntax from Python 3. In Python 3, print is a function and takes arguments like other functions (as in print(...)).
In Python 2, print is a statement, and by using parentheses you are actually passing it a tuple as its first argument (so you are printing out the Python representation of a tuple).
You can fix this in two ways.
If you add from __future__ import print_function to the top of your file, then print will behave like it does in Python 3.
Alternately, you can call it like:
print 'There are', length,'character'
You're printing a tuple (even though it may not appear that way at first glance), so the output is the repr of that tuple.
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
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 9 years ago.
When I use the print command, it prints whatever I want and then goes to a different line. For example:
print "this should be"; print "on the same line"
Should return:
this should be on the same line
but instead returns:
this should be
on the same line
More precisely I was trying to create a program with if that told me whether a number was a 2 or not
def test2(x):
if x == 2:
print "Yeah bro, that's tottaly a two"
else:
print "Nope, that is not a two. That is a (x)"
But it doesn't recognise the last (x) as the value entered, and rather prints exactly: "(x)" (the letter with the brackets). To make it work I have to write:
print "Nope, that is not a two. That is a"; print (x)
And if e.g. I enter test2(3) that gives:
Nope, that is not a two, that is a
3
So either I need to make Python recognise my (x) inside a print line as the number; or to print two separate things but on the same line.
IMPORTANT NOTE: I am using version 2.5.4
Another note: If I put print "Thing" , print "Thing2" it says "Syntax error" on the 2nd print.
In Python 3.x, you can use the end argument to the print() function to prevent a newline character from being printed:
print("Nope, that is not a two. That is a", end="")
In Python 2.x, you can use a trailing comma:
print "this should be",
print "on the same line"
You don't need this to simply print a variable, though:
print "Nope, that is not a two. That is a", x
Note that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" " in Python 3. To suppress the space character as well, you can either use
from __future__ import print_function
to get access to the Python 3 print function or use sys.stdout.write().
In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.
import sys
sys.stdout.write('hi there')
sys.stdout.write('Bob here.')
yields:
hi thereBob here.
Note that there is no newline or blank space between the two strings.
In Python 3.x, with its print() function, you can just say
print('this is a string', end="")
print(' and this is on the same line')
and get:
this is a string and this is on the same line
There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)
E.g.,
Python 2.x
print 'hi', 'there'
gives
hi there
Python 3.x
print('hi', 'there', sep='')
gives
hithere
If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try
from __future__ import print_function
print("abcd", end='')
print("efg")
results in
abcdefg
For those using 3.x, this is already built-in.
You simply need to do:
print 'lakjdfljsdf', # trailing comma
However in:
print 'lkajdlfjasd', 'ljkadfljasf'
There is implicit whitespace (ie ' ').
You also have the option of:
import sys
sys.stdout.write('some data here without a new line')
Utilize a trailing comma to prevent a new line from being presented:
print "this should be"; print "on the same line"
Should be:
print "this should be", "on the same line"
In addition, you can just attach the variable being passed to the end of the desired string by:
print "Nope, that is not a two. That is a", x
You can also use:
print "Nope, that is not a two. That is a %d" % x #assuming x is always an int
You can access additional documentation regarding string formatting utilizing the % operator (modulo).
Ok on this link it shows the last line of output that has ' around everything except the third sentence and I do not know why. This bothered me at the beginning and thought it was just a weird mistake but its on the "extra credit" so now I am even more curious.
This is because the %r formatter prints the argument in the form you may use in source code, which, for strings, means that it is quote-delimited and escaped. For boolean values, this is just True or False. To print the string as it is, use %s instead.
>>> print '%s' % '"Hello, you\'re"'
"Hello, you're"
>>> print '%r' % '"Hello, you\'re"'
'"Hello, you\'re"'
python's repr() function, which is invoked by interpolating the %r formatting directive, has the approximate effect of printing objects the way they would appear in source code.
There are several ways to format strings in python source, using single or double quotes, with backslash escapes or as raw strings, as simple, single line strings or multi line strings (in any combination). Python picks only two ways to format strings, as single or double quoted, single line strings with escapes instead of raw.
Python makes a crude attempt at picking a minimal format, with a slight bias in favor of the single quote version (since that would be one fewer keystrokes on most keyboards).
The rules are very simple. If a string contains a single quote, but no double quotes, python prints the string as it would appear in python source if it were double quoted, Otherwise it uses single quotes.
Some examples to illustrate. Note for simplicity all of the inputs use triple quotes to avoid backslash escapes.
>>> ''' Hello world '''
' Hello world '
>>> ''' "Hello world," he said. '''
' "Hello world," he said. '
>>> ''' You don't say? '''
" You don't say? "
>>> ''' "Can't we all just get along?" '''
' "Can\'t we all just get along?" '
>>>
How do I go about printin a NoneType object in Python?
# score can be a NonType object
logging.info("NEW_SCORE : "+score)
Also why is that sometime I see a comma instead of the + above?
The best approach is:
logging.info("NEW_SCORE: %s", score)
In most contexts, you'd have to use a % operator between the format string on the left and the value(s) on the right (in a tuple, if more than one). But the logging functions are special: you pass the format string as the first argument, then, one after the other, just as many arguments as needed to match the number of %s &c formatting markers in the format, and the logging functions will use the formatting operator %s as appropriate if and only if necessary -- so you don't incur any runtime overhead if your current logging level is such that, e.g., logging.info is not actually going to be shown.
Forget str calls and +-based string concatenation anyway -- even without logging's specials, %-formatting is really the way to go (in Python 2.6 or earlier; in 2.6 or later, you should also consider strings' format method, allowing clearer and more readable expression of what amounts to the same functionality).
logging.info("NEW_SCORE : " + str(score))
Proof by Python interpreter:
>>> x = None
>>> "x: " + x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'NoneType' objects
>>> "x: " + str(x)
'x: None'
QED
For print purpose,you need to str first. A comma is to print with a single space between it..For example:
print "hi guys","how are you today"
this syntax will output:
hi guys how are you today
but it will be different if your syntax like this:
print "hi guys"+"how are you today"
this syntax will output:
hi guyshow are you today
if not score==None: logging.info("NEW_SCORE : "+score)
or
logging.info("NEW_SCORE: %s" % str(score) )