PE100-09: Strings

We’ve been using strings in each of the previous modules, but we’ve accepted them as a found artifact without really getting into them and seeing how they. This module will correct that deficiency and make all of better peopleprogrammers.

Review time

Let’s take a quick look at what we’ve done so far.

String literals:   "Doug McKenzie"
String variables:  comedic_genius = "Mel Brooks"

Comparison:        if my_name == your_name:
                   if your_name != "Chuck Woolery":
Concatenation:     full_name = first_name+last_name
Repetition:        "ABC" * 20

There is a lot more we can do with strings. We can: * Index into them * Iterate over them * Slice them * Search them * Call methods that act on them…

In fact, when you look at what you can do with a string and how you do it, you suddenly realize that a string is just (conceptually) a tuple of letters.

We can index into a string:

my_name="John Belushi"
print(my_name[0])
print(my_name[len(my_name)-1])
print(my_name[-1])
J
i
i

Strings are iterables:

for char in my_name:
    print(char)
J
o
h
n
 
B
e
l
u
s
h
i

Just like a tuple, the elements of a string are immutable. Once a string is created, the characters can’t be changed.

my_name="Bob"
my_name[0]='R'
TypeError: 'str' object does not support item assignment

We can slice strings:

my_name="Michael Jordan"
print(my_name[2:4])
print(my_name[4:])
print(my_name[:2])
ch
ael Jordan
Mi

We can search into a string with the in operator:

tweet_msg = "I think synchrotrons are cool."
if "synchrotrons" in tweet_msg:
    print("found one!")
found one!

There are a huge variety of string methods. We’ll look at just a few here. Some of them are handy for validating inputs…

bolts = input("How many bolts did you install?")
if not bolts.isdigit():
    print("I was expecting something that looked like an integer")
else:
    fasteners = int(bolts)
How many bolts did you install? op
I was expecting something that looked like an integer