python-2.x

Python re.sub MULTILINE caret match

The Python docs say: re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string... So what's going on when I get the following unexpected result? >>> import re >>...

Tutorial for Python - Should I use 2.x or 3.0?

Python 3.0 is in beta with a final release coming shortly. Obviously it will take some significant time for general adoption and for it to eventually replace 2.x. I am writing a tutorial about certain aspects of programming Python. I'm wondering if I should do it in Python 2.x or 3.0? (not that the difference is huge) a 2.x tutorial ...

How to read Unicode characters from command-line arguments in Python on Windows

I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode? Example code: argv.py import sys first_arg = sys.argv[1] print first_arg print type(first_arg) print first_...

Default encoding of exception messages

The following code examines the behaviour of the float() method when fed a non-ascii symbol: import sys try: float(u'\xbd') except ValueError as e: print sys.getdefaultencoding() # in my system, this is 'ascii' print e[0].decode('latin-1') # u'invalid literal for float(): ' followed by the 1/2 (one half) character print unicode...

making python 2.6 exception backward compatible

I have the following python code: try: pr.update() except ConfigurationException as e: returnString=e.line+' '+e.errormsg This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) ...

Error while installing Poster (Python Module)

I'm trying to install Chris Atlee's python Poster library so I can upload a file using a HTTP POST query from within my script. On python 2.3, when I type # python setup.py install, I get the following error. The install continues, but I can't >>> import poster later on. byte-compiling build/bdist.linux-x86_64/egg/poster/encode.py to e...

how to print number with commas as thousands separators in Python 2.x

I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way. It does not need to be locale-specific to decide between periods and co...

python modify __metaclass__ for whole program

EDIT: Note that this is a REALLY BAD idea to do in production code. This was just an interesting thing for me. Don't do this at home! Is it possible to modify __metaclass__ variable for whole program (interpreter) in Python? This simple example is working: class ChattyType(type): def __init__(cls, name, bases, dct): print...

What does python print() function actually do?

I was looking at this question and started wondering what does the print actually do. I have never found out how to use string.decode() and string.encode() to get an unicode string "out" in the python interactive shell in the same format as the print does. No matter what I do, I get either UnicodeEncodeError or the escaped string wit...

Any way to set request headers when doing a request using urllib in Python 2.x?

I am trying to make an HTTP request in Python 2.6.4, using the urllib module. Is there any way to set the request headers? I am sure that this is possible using urllib2, but I would prefer to use urllib since it seems simpler. ...

Why can't Python handle true/false values as I expect?

As part of answering another question, I wrote the following code whose behaviour seems bizarre at first glance: print True # outputs true True = False; print True # outputs false True = True; print True # outputs false True = not True; print True # outputs true Can anyone explain this strange behaviour...

An equivalent to string.ascii_letters for unicode strings in python 2.x?

In the "string" module of the standard library, string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' Is there a similar constant which would include everything that is considered a letter in unicode? ...

Python (2.6) , List Comprehension: why is this a syntax error ?

Why is print(x) here not valid (SyntaxError) in the following list-comprehension? my_list=[1,2,3] [print(my_item) for my_item in my_list] To contrast - the following doesn't give a syntax error: def my_func(x): print(x) [my_func(my_item) for my_item in my_list] ...

__cmp__ method is this not working as expected in Python 2.x?

class x: def __init__(self,name): self.name=name def __str__(self): return self.name def __cmp__(self,other): print("cmp method called with self="+str(self)+",other="+str(other)) return self.name==other.name # return False instance1=x("hello") instance2=x("there") print(instance1==i...

Returning the first N characters of a unicode string

I have a string in unicode and I need to return the first N characters. I am doing this: result = unistring[:5] but of course the length of unicode strings != length of characters. Any ideas? The only solution is using re? Edit: More info unistring = "Μεταλλικα" #Metallica written in Greek letters result = unistring[:1] returns-> ...

Implicitly invoking parent class initializer

class A(object): def __init__(self, a, b, c): #super(A, self).__init__() super(self.__class__, self).__init__() class B(A): def __init__(self, b, c): print super(B, self) print super(self.__class__, self) #super(B, self).__init__(1, b, c) super(self.__class__, self).__init__(1, b,...

Tell if python is in interactive mode

In a python script, is there any way to tell if the interpreter is in interactive mode? This would be useful, for instance, when you run an interactive python session and import a module, slightly different code is executed (for example, log file writing is turned off, or a figure won't be produced, so you can interactively test your pro...

How to organize Python modules for PyPI to support 2.x and 3.x

I have a Python module that I would like to upload to PyPI. So far, it is working for Python 2.x. It shouldn't be too hard to write a version for 3.x now. But, after following guidelines for making modules in these places: Distributing Python Modules The Hitchhiker’s Guide to Packaging it's not clear to me how to support multiple so...

Identifying that a variable is a new-style class in Python?

I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out. import types class oldclass: pass def test(): o = oldclass() if type(o) is types.InstanceType: print 'Is old-style' else: print 'Is NOT old-...

How do I convert a unicode to a string at the Python level?

The following unicode and string can exist on their own if defined explicitly: >>> value_str='Andr\xc3\xa9' >>> value_uni=u'Andr\xc3\xa9' If I only have u'Andr\xc3\xa9' assigned to a variable like above, how do I convert it to 'Andr\xc3\xa9' in Python 2.5 or 2.6? EDIT: I did the following: >>> value_uni.encode('latin-1') 'Andr\xc3\...