Posts Tagged ‘py’

Reversing a string in Python

Posted: 25th April 2013 by Tim in Python
Tags: , , , , , , , ,

If you need to reverse a string in python, the easiest way is to do use the my_string[::-1] syntax. For example, to print a reversed string, you could write: my_string = “ABCDE” print my_string[::-1] So what is this doing? The square bracket syntax is used for returning a substring. This works like so: [<start>:<end>:<step>]. If […]

Reading environment variables in python

Posted: 13th November 2012 by Tim in Python
Tags: , , , , , ,

Shell envronment variables contain many useful paths and settings. At times you may want to use these variables from within a python program. This can be done via the os.path.expandvars(<var>) call, defined in os.path. For example, the following program: import os.path print os.path.expandvars(‘$SHELL’); Will print (on my machine): /bin/bash