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
Related
I am trying to print values of two variables in Python. My question is when I am trying to print the values in this way like print(a),print(b) in Jupyter notebook, I am getting the values of the variables but the output is also giving a tuple type of result which is giving as (None,None). I want to know why it is giving that (None,None) output. I should have got result like (value1,value2). Someone please advise. Also, please let me know how to the result in tuple format like (2,5) where a=2,b=5. enter image description here
This is just a side effect of the command line. You wouldn't see this if you run a program. If you just type an expression in a command line:
>>> 3
3
Python shows you the result of that expression. If the expression returns None, Python shows you nothing. So:
>>> time.sleep(3)
>>> print("hello")
hello
>>>
time.sleep returns None, so you see nothing. You see the side effect of the print statement, but because the print statement returned None, it shows you nothing else. But when you do:
>>> print(a),print(b)
2
5
(None,None)
>>>
Both print statements return None, and because you've used a comma, the result of that expression is a tuple containing two None values. So, you see the side effect of the print statements, and because your expression ((None,None)) is not exactly the same as None, Python prints it for you.
The comma operator is NOT the right way to separate multiple statements, like you do in C. In Python, the comma operator builds tuples. If you want to separate multiple statements on a line, use semi-colon:
>>> print(a);print(b)
2
5
>>>
It's a part of Jupyter called autocall. There is some documentation on it here:
https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-autocall
To split up your call either ";" or print((a,b)). Not sure what you are trying to achieve.
I am trying to call a variable into file-path but i'm unable to get it.
file-path mean is = "/sys/class/net/bond0/speed" , where "bond0" is dynamic.
In the below code , the Current_inf is producing the values like "bond0" etc its changeable.
>>> import subprocess
>>> import netifaces
>>> import socket
>>> import re
>>> Current_inf = netifaces.gateways()['default'][netifaces.AF_INET][1]
>>> print Current_inf
bond0.180
>>> subprocess.Popen(str['/sys/class/net/%s%s'(Current_inf)/speed])
Below is the shell command what i'm trying to achieve via python
# cat /sys/class/net/bond0/speed
2000
any help or suggestions will much appreciated.
First, you don't need Popen, you need check_output to get the result directly.
Second, you're trying to convert a list in str (not sure since str[...] is not valid syntax). Drop str
Third, that's not how you format a string using % (you could also use str.format, which is even better)
My proposal:
speed = subprocess.check_output('/sys/class/net/%s/speed' % (Current_inf)).rstrip()
Upon successful execution, speed holds the return value minus the trailing linefeed (thanks to rstrip())
This is the solution to my original Question:
subprocess.check_output(['cat', '/sys/class/net/{}/speed'.format(Current_inf)])
oR
open('/sys/class/net/{}/speed' .format(Current_inf)).read().strip()
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
I'm messing around with python, following this tutorial:
http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Hello,_World
According to it, my output for the following code:
print("Single String")
print("Concat", "String")
Should look like this:
Single String
Concat String
But it looks like this:
Single String
('Concat', 'String')
Why is this? I'm on OSX with Python 2.6.
EDIT: I just realized the guide is for 3.0, and I have 2.6. Is that causing the issue? What is the quickest way to upgrade my Python install?
EDIT 2: An upgrade fixed it :) Accepted answer explains the differences.
print("Concat", "String")
This is a tuple. When you put the , it becomes a tuple and hence Python outputs it the same way.
>>> t = ('Let', 'Us', 'Test')
>>> type(t)
<type 'tuple'>
A tuple consists of a number of values separated by commas.
Not an answer to the OP's original question, which I think sukhbir answered quite well, but to the follow up question.
I believe the quickest way to upgrade would be to go to the Python website and download v3.
If you are using Python 2.x you can just use
print "Single", "String"
Python 3.x changes the way print works, previously it was a statement and now it is a function.
For compatibility in Python 2.7 you can use placeholders
print('%s %s')%("Concat", "String")
The reason is that you are running a Python 3 tutorial with Python 2.
In Python 2.6 you can also say
from __future__ import print_statement
to get the 3.x syntax.
To get the behaviour you want, you need to print a string representation of the tuple. You can get this by using the join method on strings:
print ' '.join(('a', 'b'))
The reason the behaviour is not as expected is that in Python 2, print is a keyword. In Python 3, it has been replaced by a function (also print), so the latter syntax calls the function instead of printing a tuple. You can replicate the behaviour you have see in Python 3 with
print(('a', 'b'))
One set of parentheses for the function call, and one for the tuple.