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.
>>> print creature m
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’.
>>> print creature[x-1] k
An expression can exist inside the index operator. Got it? Good!
Sometimes you need to know the length of a string.
>>> 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.
for letter in food:
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.
count = 0
for letter in bigword:
if letter == ‘i’:
count = count + 1
Slicing the Python String
You can slice a Python string to get a substring.
>>> 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.
You can look for values.
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.
>>> print greet.lower()
how are you?
You can look for a character and know its index value.
Correct! Python start at the sixth index value of the string. Remember, index values start a zero!
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.
>>> print color
>>> print color.lstrip()
See how that works? Great!
Sometimes you need to extract lines that begin with a certain string.
These examples show how Python is really good at parsing data.