Python print() output discrepancy - python

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.

Related

Can I override u-strings (u'example') in Python 2?

In debugging upgrading to Python 3, it would be useful to be able to override the u'' string prefix to call my own function or replace with a non-u string.
I've tried things like unichr = chr which is useful for my debugging but doesn't accomplish the above.
module.uprefix = str is the type of solution I'm looking for.
You basically can't; as others have noted in the comments, the u-prefix is handled very early, well before anything where an in-code assignment would take effect.
About the best you could do is use ast.parse to read a module on disk (without importing it) and find all the u'' strings; it distinguishes the prefixes. That would help you find them in a Python-aware way, more reliably than just searching for u' and u", but the difference probably wouldn't be large, especially if you search with word boundaries (regex \bu['"]). Unless you somehow have a lot of u' and u" in your program that aren't the prefixes?
>>> ast.dump(ast.parse('"abc"', mode='eval'))
"Expression(body=Constant(value='abc', kind=None))"
>>> ast.dump(ast.parse('u"abc"', mode='eval'))
"Expression(body=Constant(value='abc', kind='u'))"
Per the comments, what are you trying to do? I've migrated a lot of code from Python 2 to Python 3 and never needed this... There may be a different way to achieve the same goal?

Proper way to concatenate mixed type variables WITHOUT using f statement

What would be the proper way to combine something like this?
thisID=12345
myVar= '<!',thisID,'!>'
Expected result: <! 12345 !>
Python is using the commas to convert into a tuple, but I need them to be treated as concatenators instead
EDIT:
My version didnt have f statement, so in case anyone else is needing a similar concat without using f, this worked for me
thisNewID=12345
myVar="<! {thisNewID} !>".format(thisNewID=thisNewID)
The easier approach would probably to use an f-string:
myVar= f'<! {thisID} !>'
thisID=12345
myVar= '<!'+str(thisID)+'!>'
Here's a more complete answer that I would have appreciated more than all the downvotes.
The f statement does not work on every version of python.
Newer versions can use
thisNewID=12345
myVar= f'<! {thisID} !>'
My version happened to be 3.3 and that did NOT work, but below syntax did.
myVar="<! {thisNewID} !>".format(thisNewID=thisNewID)
To properly answer this question, an experienced person would first have to ask what version, since this IS version specific syntax.
There are several ways to do it.
I recommend to use str(int) + 'string'.
FYI, you can have a look at this.
https://www.askpython.com/python/string/python-concatenate-string-and-int

In Julia, insert commas into integers for printing like Python 3.6+

I want to insert commas into large integers for printing.
julia> println(123456789) # Some kind of flag/feature inserts commas.
"123,456,789"
In Python 3.6+ this is easy to do:
>>> print(f"{123456789:,d}")
123,456,789
However, it does not appear that the standard Julia print/println functions have this feature at the present time. What can I do using just the print/println functions?
I guess the most straightforward way in some languages would be to use the ' format modifier in printf. I Julia this WOULD look like so:
using Printf # a stdlib that ships with julia which defines #printf
#printf "%'d" 12345678
However, unfortunately, this flag is not yet supported as you can see from the error you'll get:
julia> #printf "%'d" 12345678
ERROR: LoadError: printf format flag ' not yet supported
If you like this feature, maybe you should think about adding it to the Printf stdlib so that everyone would benefit from it. I don't know how difficult this would be though.
UPDATE: Note that although the macro is defined in stdlib Printf, the error above is explicitly thrown in Base/printf.jl:48. I also filed an issue here
Here is a function based on a Regex from "Regular Expressions Cookbook," by Goyvaerts and Levithan, O'Reilly, 2nd Ed, p. 402, that inserts commas into integers returning a string.
function commas(num::Integer)
str = string(num)
return replace(str, r"(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" => ",")
end
println(commas(123456789))
println(commas(123))
println(commas(123456789123456789123456789123456789))
""" Output
123,456,789
123
123,456,789,123,456,789,123,456,789,123,456,789
"""

2.7.6 python version needs parenthesis to print?

Is it normal for me to use parenthesis when making a call to print in Python 2.7? I thought only 3 onwards needs to do this?
without the parenthesis I get a syntax error.
SyntaxError: invalid syntax
but with parenthesis, it works.
I was under the assumption that 2.7 doesn't need parenthesis to print?
Your impression is correct, it's not needed (unless of course you import print_function von __future__!). However, it's not prohibited either. print is followed by an expression, and (sys.version) is a valid expression as much as sys.version is. Note that (x) does not create a tuple containing x (that would be (x,)).

Python 3.3: separation argument (sep) giving an error

I am very new to programming and I'm starting out with Python. I tried to look up my question here but didn't really find anything.
I'm trying to work a very simple print command but I'm getting an error for some reason that I don't understand.
last = 'smith'
middle = 'paul'
first = 'john'
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
According to the answer in the book, this should be right, but every time I try to run it, I get an error with the 'sep':
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
^
SyntaxError: invalid syntax
Can someone tell me what I'm doing wrong. for what it's worth I'm using PyScripter.
[EDIT]
Thanks for that. I found out that I'm using Python 2.7.3 instead of 3.3. So I looked up the manual to see how the separator works. It seems to me that the only difference is with the square bracket. The manual describes the print function as :
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
So I changed my print command and added the square bracket:
print ([first.capitalize(),middle.capitalize(),last.capitalize()] [, sep='\t'])
but unfortunately this doesn't work either as I get an error that highlights the square brackets around sep='\t'. Even when I take the brackets out, the error doesn't go away.
I'm not sure what I'm doing wrong, it seems like it should be very simple.
You aren't actually using Python 3, you just think you are. Try:
import sys
print(sys.version)
and see what comes out. The Python 2 print ... statement (not print(...) function in Python 3) interprets this as
print (first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
which is trying to print a tuple with a keyword argument, thus the syntax error on sep

Categories