What exactly do “u” and “r” string prefixes do, and what are raw string literals?

There’s not really any “raw string“; there are raw string literals, which are exactly the string literals marked by an ‘r’ before the opening quote. A “raw string literal” is a slightly different syntax for a string literal, in which a backslash, \, is taken as meaning “just a backslash” (except when it comes right … Read more

What is the difference between range and xrange functions in Python 2.X?

In Python 2.x: range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements. xrange is a sequence object that evaluates lazily. In Python 3: range does the equivalent of Python 2’s xrange. To get the list, you have to explicitly use list(range(…)). xrange no longer exists.

What is __future__ in Python used for and how/when to use it, and how it works

With __future__ module’s inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords. E.g., for using context managers, you had to do from __future__ import with_statement in 2.5, as the with keyword was new and shouldn’t be used as variable names any longer. In order to use with as … Read more

What are the differences between the urllib, urllib2, urllib3 and requests module?

I know it’s been said already, but I’d highly recommend the requests Python package. If you’ve used languages other than python, you’re probably thinking urllib and urllib2 are easy to use, not much code, and highly capable, that’s how I used to think. But the requests package is so unbelievably useful and short that everyone … Read more

UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 20: ordinal not in range(128)

You need to read the Python Unicode HOWTO. This error is the very first example. Basically, stop using str to convert from unicode to encoded text / bytes. Instead, properly use .encode() to encode the string: p.agent_info = u’ ‘.join((agent_contact, agent_telno)).encode(‘utf-8’).strip() or work entirely in unicode.

tech