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,)).
Related
I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)
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
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.
I was intrigued by this answer to my question about getting vim to highlight unmatched brackets in python code. Specifically, I'm talking about the second part of his answer where he mentions that the C syntax highlighting is actually flagging as an error any instance of curly braces inside parens. It is an unobtrusive cue that you have unclosed parens when all of your downstream curly braces light up in red.
That trick works because C syntax doesn't allow curly braces inside parentheses. To satisfy my (morbid?) curiosity, can I do something similar with python code? Is there anything in python syntax that isn't legal inside parentheses?
Note: I'm not trolling for a better answer to my other question (there are plenty of good answers there already). I'm merely curious if this trick is even possible with python code.
Any Python statement (import, if, for, while, def, class etc.) cannot be in the parentheses:
In [1]: (import sys)
------------------------------------------------------------
File "<ipython console>", line 1
(import sys)
^
<type 'exceptions.SyntaxError'>: invalid syntax
Here's an exact answer:
http://docs.python.org/reference/expressions.html#grammar-token-expression_list
http://docs.python.org/reference/compound_stmts.html#function
I'm not sure what are you trying to do, but how about "def" or "class"?
this snippet is valid when it's not inside parenthesis
class dummy: pass
I am trying to convert the following Perl regex I found in the Video::Filename Perl module to a Python 2.5.4 regex to parse a filename
# Perl > v5.10
re => '^(?:(?<name>.*?)[\/\s._-]*)?(?<openb>\[)?(?<season>\d{1,2})[x\/](?<episode>\d{1,2})(?:-(?:\k<season>x)?(?<endep>\d{1,2}))?(?(<openb>)\])(?:[\s._-]*(?<epname>[^\/]+?))?$',
I would like to use named groups too, and I know in Python the regex extension for named groups is different, but I am not 100% sure on the syntax.
This is what I tried:
# Python (not working)
r = re.compile(r'^(?:(?P<name>.*?)[\/\s._-]*)?(?P<openb>\[)?(?P<season>\d{1,2})[x\/](?P<episode>\d{1,2})(?:-(?:\kP<season>x)?(?P<endep>\d{1,2}))?(?(P<openb>)\])(?:[\s._-]*(?P<epname>[^\/]+?))?$')
The error I get:
raise error, v # invalid expression
sre_constants.error: bad character in group name
For example, this one I managed to convert and it works. But the one above I can't seem to get right. I get a compilation error in Python.
# Perl:
re => '^(?:(?<name>.*?)[\/\s._-]+)?(?:s|se|season|series)[\s._-]?(?<season>\d{1,2})[x\/\s._-]*(?:e|ep|episode|[\/\s._-]+)[\s._-]?(?<episode>\d{1,2})(?:-?(?:(?:e|ep)[\s._]*)?(?<endep>\d{1,2}))?(?:[\s._]?(?:p|part)[\s._]?(?<part>\d+))?(?<subep>[a-z])?(?:[\/\s._-]*(?<epname>[^\/]+?))?$',
# Python (working):
r = re.compile(r'^(?:(?P<name>.*?)[\/\s._-]+)?(?:s|se|season|series)[\s._-]?(?P<season>\d{1,2})[x\/\s._-]*(?:e|ep|episode|[\/\s._-]+)[\s._-]?(?P<episode>\d{1,2})(?:-?(?:(?:e|ep)[\s._]*)?(?P<endep>\d{1,2}))?(?:[\s._]?(?:p|part)[\s._]?(?P<part>\d+))?(?P<subep>[a-z])?(?:[\/\s._-]*(?P<epname>[^\/]+?))?$')
I am not sure where to start looking.
There are 2 problems with your translation. First of all, the second mention of openb has extra parenthesis around it making it a conditional expression, not a named expression.
Next is that you didn't translate the \k<season> backreference, Python uses (P=season) to match the same. The following compiles for me:
r = re.compile(r'^(?:(?P<name>.*?)[\/\s._-]*)?(?P<openb>\[)?(?P<season>\d{1,2})[x\/](?P<episode>\d{1,2})(?:-(?:(?P=season)x)?(?P<endep>\d{1,2}))?(?(openb)\])(?:[\s._-]*(?P<epname>[^\/]+?))?$')
If I were you, I'd use re.VERBOSE to split this expression over multiple lines and add copious documentation so you can keep understanding the expression in the future if this is something that needs to remain maintainable though.
(edited after realising the second openb reference was a conditional expression, and to properly translate the backreference).
I found the offending part but can't figure out what exactly is wrong without wrapping my mind around the whole thing.
r = re.compile(r'^(?:(?P<name>.*?)[\/\s._-]*)?(?P<openb>\[)?(?P<season>\d{1,2})[x\/](?P<episode>\d{1,2})(?:-(?:\kP<season>x)?(?P<endep>\d{1,2}))?
(?(P<openb>)\]) // this part here causes the error message
(?:[\s._-]*(?P<epname>[^\/]+?))?$')
The problem seems to be with the fact that group names in python must be valid python identifiers (check documentation). The parentheses seem to be the problem. Removing them gives
(?(P<openb>)\]) //with parentheses
(?P<openb>\]) //without parentheses
redefinition of group name 'openb' as group 6; was group 2
Those regexps are the product of a sick an twisted mind... :-)
Anyway, (?()) are conditions in both Python and Perl, and the perl syntax above looks like it should be the same as the Python syntax, i.e., it evaluates as true of the group named exists.
Where to start looking? The documentation for the modules are here:
http://docs.python.org/library/re.html
http://www.perl.com/doc/manual/html/pod/perlre.html
I may be wrong but you tried to get the backreference using :
(?:\k<season>x)
Isn't the syntax \g<name> in Python ?