Comp 112

Lecture 4

Strings and Methods



String Review

We know that a string is a sequence of characters.

So far we can:

Now, we’ll learn how to do more sophisticated string manipulations.

String Indexing

Negative Indices

Index Bounds

In order to be valid index for a string s,

String Processing

Combining looping with indexing to process a string:

def reverse_string (s) :
    signature: str -> str
    reverses a string
    i  =  0             #  index counter
    acc  =  ''          #  result accumulator
    while i < len (s) :
        acc  =  s [i] + acc
        i  +=  1
    return acc


Slice Shorthands

For convenience, you can omit either index:

Namespaces and Methods


String Functions

Many useful functions for strings are located in the “str” namespace, including:


Method syntax is more concise but rather restrictive. It works only for functions that:

String Methods

All of the functions from the “str” namespace that we just saw can be written as methods:

Additional String Operations

String Comparisons

in Operator

Notice that the empty string ('') is in every string, even itself:

for Loops

Example: Counting Vowels

def is_vowel (char) :
    signature: str -> bool
    predicate for vowels
    return (len (char) == 1) and (char.lower () in 'aeiou')

To Do This Week: