More examples on Python strings

So far we’ve looked at how to manipulate strings using basic Python operations. In this section we are going to learn few more about strings by using for and while loops.

Traversal

In computation one often involves processing a string one character at a time. This pattern of processing is called a traversal, which can be demonstrated as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
"""
/lectureNote/chapters/chapt03/codes/examples/lists/banana_while.py

"""

fruit = 'banana'
index = 0
while index < len(fruit):
    letter = fruit[index]
    print letter
    index += 1
    

The output should look like:

b
a
n
a
n
a

Another way to traverse a string is to use a for loop:

1
2
3
4
5
6
7
8
9
"""
/lectureNote/chapters/chapt03/codes/examples/lists/banana_for.py

"""
fruit = 'banana'

for char in fruit:
    print char
    

This should generate the same ouptut as the while loop case.

Concatenation (string addition)

The string addition in Python operates to produce a concatenation of all strings. We can use for loop to generate a series of names in alphabetical order. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
"""
/lectureNote/chapters/chapt03/codes/examples/lists/pref_suff.py

"""

prefixes = 'JKLMNOPQ'
suffix    = 'ack'

for letter in prefixes:
    print letter + suffix

The output is:

$ python pref_suff.py
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

Searching and counting

We can use while loop to search a character in a given word.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""
/lectureNote/chapters/chapt03/codes/examples/strings/searching.py

"""

def find(word,letter):
    index = 0
    count = 0
    wordLoc = list()
    # You can also use
    # wordLoc = []
    while index < len(word):
        if word[index] == letter:
            count += 1
            wordLoc.append(index)
        index += 1
    return count,wordLoc

print find('apple','a')
print find('apple','p')
print find('apple','l')
print find('apple','e')

The output looks like:

$ python searching.py
(1, [0])
(2, [1, 2])
(1, [3])
(1, [4])

String methods

As we have seen some of the examples of string methods, a method is similar to a function. It takes arguments and returns a value. But the syntax is different. Let’s consider the string method upper which takes a string and returns a new string with all uppercase letters

One might try the usual function syntax, upper(word), which, unfortunately, is not the right way of the method sysntax. Instead, we use word.upper():

>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parenthesis indicate that this method takes no argument.

This method is called an invocation; in this case, we would say that we are invoking upper on the word.

Another string method example is find:

>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1

To find substrings, rather than a character, we can do:

>>> word.find('na')
2

One can also specify the starting index as a second argument:

>>> word.find('na',3)
4

The third argument specifies the stopping index:

>>> word.find('na',3,4)
-1

The negetive value -1 appears because na does not appear in the index range of [3,4).

The in operator

The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:

>>> 'a' in 'banana'
True
>>> 'b' in 'tiger'
False

Here is an example to use in:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
"""
/lectureNote/chapters/chapt03/codes/examples/lists/in_both.py

"""

def in_both(word1, word2):
    for letter in word1:
        if letter in word2:
            print letter

in_both('apples','oranges')

The output is:

a
e
s

String comparison

The relational operators work on strings:

>>> a,b,c,d='apple','orange','apple','adobe'

>>> a == b
False

>>> a == c
True

>>> a is c
True

>> a is not c
False

>>> a>b
False

>>> a < b
True

>>> a<c
False

>>> a<d
False

As can be seen above, Python compares string based on the lexicographical order using ASCII value of the chracters.

Mixed type comparison

When comparing two things that are of the same type the ordering is done in the natural way, that is, lexicographical ordering for string comparison and numerical ordering for numbers.

In addition, Python also can compare non-compatible objects such as:

  • numeric type and non-numeric types (numeric is always smaller)
  • two incompatible objects that are non-numeric (alphabetical order of their type names: list (e.g., []), string (e.g., 'foo'), tuple (()), dictionary ({})

Examples are:

>>> 5. < 4
False

>>> 5. < 4.
False

>>> 5 < 'apple'
True

>>> -0.1 > '1ade159'
False

>>> 5 < [1,'a',0]
True

>>> 5 < (1,'a',0)
True

>>> 5 < {}
True

>>> (1,'a',0 ) < {}  # 'tuple' > 'dictionary'
False

>>> (1,'a',0 ) < [1,'a',0]  # 'tuple' > 'list'
False

>>> (1,'a',0 ) < 'foo'  # 'tuple' > 'string'
False

>>> 'a1ple' < 'apple'  # 1 < 'p'
True

Note

Write a simple routine to confirm the order goes as: tuple > string > list > dictionary > number.