Tuesday, June 18, 2013

Useful Python string methods

The Python built-in string type has many useful methods that can make your life easier. You can navigate all of them, the methods in the Python documentation: http://docs.python.org/2/library/stdtypes.html#string-methods

One of those is the method that check if a string is a number. For example, you have a string, let's call it:

my_str = "Linux101"

 The first 5 characters stands for the subject, and the last 3 characters stands for the session of the class. We have a dictionary of teachers:



TEACHERS = {'Linux': 'Linus Torvalds', 'iOS': 'Steve Jobs', 'Windows': 'Bill Gates'}

and 2 dictionary of periods, one for numeric periods, on for string periods:

NUM_PERIODS = {101: '8am', 102: '1pm'}

STR_PERIODS = {'special101': '9am', 'special102': '2pm'}

Now, I'am gonna parse the string to figure out the teacher and when the class starts :

subject = my_str[:5] # get the first 5 characters of the string

session = my_str[5:] # get the last characters of the string from the character #5

Because all of the items of TEACHERS are string so we can simply get the teacher:

teacher_name  = TEACHERS[subject] # 'Linus Torvalds'

We have to check if the session is integer by using isdigit() method:

if session.isdigit():
    period = NUM_PERIODS[int(session)]
else:
   period = STR_PERIODS[session]


\m/\m/\m/