Python Regular expression – r’^$’  explanation and it’s use

In Python, r’^$’  is a regular expression that matches an empty line

This looks like a regular expression (regex) commonly used in Django URL configurations.

The ‘r’ in front tells Python the expression is a raw string. In a raw string, escape sequences are not parsed. For example, ‘\n’ is a single newline character. But, r’\n’ would be two characters: a backslash and an ‘n’.

Raw strings are handy in regex, in which the backslash is used often for its own purposes. Using ‘[\\w]’ versus r'[\w]’ results in easier to read expressions. This is more salient when you’re escaping backslashes within your regular expression: ‘[\\\\]?’ (shudders).

The ‘^$’ is the actual regular expression, and represents an empty line. The ‘^’ indicates the start of a line, and the ‘$’ indicated the end of a line. Having nothing between the two therefore matches an empty line.

In Django this expression will usually appear at the bottom of your urlpatterns list. It will catch all URLs that weren’t matched by the preceding patterns.

For this particular case, the raw string was unnecessary. Having it here will make it more consistent with urlpatterns that do benefit from being a raw string.

Example: The example code below attempts to explain this, the two entries in the list that match are the completely empty string and the string with just a newline character:

 import re
 regexp = r'^$'
 example_strings = [
   'this regular expression should just match empty lines',
   'the r prefix just denotes a raw string (to ignore special charcters)',
   'the ^ looks for the start of a line',
   'the $ looks for the end of a line',
   'lets try an empty line to test that theory',
   '',
   'and a line with just a newline character',
   '\n']
 for eg in example_strings:
    print('checking: ' + eg)
    if re.match(regexp, eg):
       print(' it matches')
    else:
      print(' no match')
Advertisements

Python & pip Windows installation

Python install

At the time of this writing is Python 2.* compatible. This could be/probably will be changing in the future (spring 2015?).

Installation of Python itself should be fairly straight-forward.

  • Download and execute the latest Python 2.* installation package from here.
    At the time of this writing, Python 2.7.8 is the latest.
    While either 32-bit (x86) or 64-bit (x86-64) versions should work just fine, I tend to gravitate to 32-bit installs as I have encountered other libraries/modules in the past that only offered 32-bit versions. I have no idea if those modules that pushed me to 32-bit in the past still do not support 64-bit, but I’m a creature of habit.
  • Verify a successful installation by opening a command prompt window and navigating to your Python installation directory (default is C:\Python27). Type python from this location to launch the Python interpreter.
    Microsoft Windows [Version 6.2.9200]
    (c) 2012 Microsoft Corporation. All rights reserved.
    
    C:\Users\Username>cd C:\Python27
    
    C:\Python27>python
    Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
    32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    
  • It would be nice to be able to run Python from any location without having to constantly reference the full installation path name. This can by done by adding the Python installation path to Windows’ PATH ENVIRONMENT VARIABLE
    *In Windows 7 and Windows 8, simply searching for “environment variables” will present the option to Edit the system environment variables. This will open the System Properties / Advanced tab
    *In Windows XP, right click on My Computer->Properties to open System Properties and click on the Advanced tab.
  1. On the System Properties / Advanced tab, click Environment Variables to open User Variables and System Variables
  2. Create a new System Variable named Variable name: PYTHON_HOME and Variable value: c:\Python27 (or whatever your installation path was)
  3. Find the system variable called Path and click Edit
  4. Add the following text to the end of the Variable value:;%PYTHON_HOME%\;%PYTHON_HOME%\Scripts\ 
  5. Verify a successful environment variable update by opening a new command prompt window (important!) and typing python from any location
    Microsoft Windows [Version 6.2.9200]
    (c) 2012 Microsoft Corporation. All rights reserved.
    
    C:\Users\Username>python
    Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
    32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    

Pip install

The easiest way to install the python modules and keep them up-to-date is with a Python-based package manager called Pip

There are many methods for getting Pip installed, but my preferred method is the following:

  • Download get-pip.py to a folder on your computer. Open a command prompt window and navigate to the folder containing get-pip.py. Then run python get-pip.py. This will install pip.
  • Verify a successful installation by opening a command prompt window and navigating to your Python installation’s script directory (default is C:\Python27\Scripts). Type pip freeze from this location to launch the Python interpreter.
    pip freeze displays the version number of all modules installed in your Python non-standard library; On a fresh install, pip freeze probably won’t have much info to show but we’re more interested in any errors that might pop up here than the actual content

    Microsoft Windows [Version 6.2.9200]
    (c) 2012 Microsoft Corporation. All rights reserved.
    
    C:\Users\Username>cd c:\Python27\Scripts
    
    c:\Python27\Scripts>pip freeze
    antiorm==1.1.1
    enum34==1.0
    requests==2.3.0
    virtualenv==1.11.6
    
  • It would be nice to be able to run Pip from any location without having to constantly reference the full installation path name. If you followed the Python installation instructions above, then you’ve already got the pip install location (default = C:\Python27\Scripts) in your Windows’ PATH ENVIRONMENT VARIABLE. If you did not follow those steps, refer to them above now.
  • Verify a successful environment variable update by opening a new command prompt window (important!) and typing pip freeze from any location
    Microsoft Windows [Version 6.2.9200]
    (c) 2012 Microsoft Corporation. All rights reserved.
    
    C:\Users\Username>pip freeze
    antiorm==1.1.1
    enum34==1.0
    requests==2.3.0
    virtualenv==1.11.6

Difference between del, remove and pop methods in python list

del to remove an element by index

pop() to remove it by index if you need the returned value

remove() to delete an element by value.

The latter requires searching the list, and raises ValueError if no such value occurs in the list.

When deleting index i from a list of n elements, the computational complexities of these methods are

del     O(n - i)
pop     O(n - i)
remove  O(n)

Read the examples to understand quickly:

remove removes the first matching value, not a specific index:

>>> a = [0, 2, 2, 3]
>>> a.remove(2)
>>> a
[0, 2, 3]

del removes a specific index:

>>> a = [3, 2, 2, 1]
>>> del a[1]
[3, 2, 1]

and pop returns the removed element:

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

Their error modes are different too:

>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range