The Python String – Parse It!

A Python string is a sequence of characters. You can use single or double quotes to delimit a string.

We can look inside a Python string with the index operator. Use the square brackets for this, []. You must know that the index value is an integer and always starts at zero.

>>> creature = ‘monkey’
>>> print creature[0]

The output is m because the index value of a string always starts at zero. In other words, m is the first index value of the string ‘monkey’.

>>> x = 4
>>> print creature[x-1]

An expression can exist inside the index operator. Got it? Good!

Sometimes you need to know the length of a string.

>>> l = len(animal)
>>> print l

That’s right! The string ‘monkey’ has six characters. Note that len is a built-in function. It’s already been written for us, we just have to apply it.

You can loop through strings. The following is Python program to loop through a particular Python string.

food = ‘pizza’
for letter in food:
++++print letter

In the above program, the word letter is being used as an iteration variable.

You can write a Python program to count the occurrence of a letter in a string.

bigword = ‘supercalifragilisticexpialidocious’
count = 0
for letter in bigword:
++++if letter == ‘i’:
++++count = count + 1
++++print count

Slicing the Python String

You can slice a Python string to get a substring.

>>> bigword = ‘supercalifragilisticexpialidocious’
>>> slice = bigword[0:5]
>>> print slice

You can see that it will slice up to, but not including the second index value. The fifth index value is the letter c, but that is not include in our slice.

If you omit a the first or second index value, it will assume the beginning or end respectively.

>>> slice = bigword[:]
>>> print slice

You can look for values.

>>> ‘x’ in bigword

Yes indeed! The letter x is in supercalifragilisticexpialidocious.

There is an extensive Python string library. These are built-in functions we can invoke on strings.

>>> greet = “HOw aRe YOu?”
>>> print greet.lower()
how are you?

You can look for a character and know its index value.

>>>idea = ‘Learn Python Programming Language’
>>>print idea.find(‘Python’)

Correct! Python start at the sixth index value of the string. Remember, index values start a zero!

Stripping Whitespace

You need to know how to remove whitespace at the beginning or end of strings. These are lstrip, rstrip, and strip. They remove whitespace from the left, right, and both sides respectively.

>>> color = ‘ blue’
>>> print color
>>> print color.lstrip()

See how that works? Great!

Sometimes you need to extract lines that begin with a certain string.

>>> line = ‘Email message sent at….’
>>> line.startswith(‘Email’)

These examples show how Python is really good at parsing data.

Leave a Reply

Your email address will not be published. Required fields are marked *