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.
Related
message = "Hello World!"
vs
message = ("Hello World!")
As far as I have tested, both get interpreted with the same output. I've just started to learn python and wondering if those parentheses have any impact.
Both the implementations are same.
message= "Hello World!"
print(type(message))
Output: <class 'str'>
message = ("Hello World!")
print(type(message))
Output: <class 'str'>
Adding parenthesis to a string don't automatically make them tuples. You need to add a comma after the string to indicate to python that it should be a tuple.
message = ("Hello World!",)
print(type(message))
Output:<class 'tuple'>
Just like in a mathematical expression, parentheses don't always change the output in Python.
5 + 4 == (5 + 4) == ((5) + ((4)))
It isn't necessary to use parentheses to assign values to variables like in your question. In general however, its not always a bad idea to use parentheses even if they don't change the output of the code - if the order of operations is not perfectly clear, parentheses will make it obvious.
As one of the answers above mentioned tuples and you indicated you are new to python; I might add that in python having something to the right of an equals sign in parentheses often indicates you are trying to make a tuple. However a tuple requires at least one comma so the interpreter can figure out you are in fact making a tuple, even with only one entry.
In your example putting a string in parentheses has no effect, and probable should not done just because it would not be expected by other python developers. (Not pythonic)
A simple code like this:
print("sfjeorf",4,"fefa",5,)
I run this in jupyter, using python. And the result is:
('sfjeorf', '4', 'fefa', '5')
What I should do to get rid of the quotes and the brackets so that the result is shown like:
sfjeorf4fefa5
You're using Python 2, which doesn't take () around the arguments, so it thinks you are printing a tuple. Use the following or switch to Python 3, where print became a function instead of a statement.
print "sfjeorf",4,"fefa",5
Getting rid of the spaces to get your requested output is trickier. Easiest in Python 2 is to import the print function implementation:
>>> from __future__ import print_function
>>> print("sfjeorf",4,"fefa",5)
sfjeorf 4 fefa 5
>>> print("sfjeorf",4,"fefa",5,sep='')
sfjeorf4fefa5
In this kind of situation I prefer to use string.format() to have more control of the output. Take a look on how the code would be:
>>> print('{}{}{}{}'.format("sfjeorf",4,"fefa",5,))
sfjeorf4fefa5
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)
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
I am new to Python. I'm running Raspbian and calling a Python script this way:
python testarguments.py "Here is a test parameter"
My script:
import sys
print sys.argv[1:]
Output:
['Here is a test parameter']
Question:
What is the most efficient way to remove beginning and ending brackets and single quotes from sys.argv output?
You are slicing with
sys.argv[1:]
It means that get all the elements from 1 till the end of the sequence. That is why it creates a new list.
To get only the first item, simply do
sys.argv[1]
This will get the element at index 1.
The : sort of means 'and onwards' so it of course will return a list. Just do:
>>> sys.argv[1]
'Here is a test parameter'
Thus returning your first argument to executing the program, not a part of the list.
The other answers have addressed the actual issue for you, but in case you ever do encounter a string that contains characters you want to remove (like square brackets, for example), you could do the following:
my_str = "['Here is a test parameter']"
my_str.translate(None, "[]")
In other words, if the output you saw were actually a string, you could use the translate method to get what you wanted.