Lecture 07 Strings

Joseph Haugh

University of New Mexico

Free Recall

  • Get out a sheet of paper or open a text editor
  • For 2 minutes write down whatever comes to mind about the last class
    • This could be topics you learned
    • Questions you had
    • Connections you made

Start Reading

  • Let’s start by reading chapter 7A
  • Take about 10-15 minutes to do this

Strings So Far

  • So far we have seen many instances of strings
  • We have discussed them as sequence of characters
  • We haven’t yet seen how to extract from that sequence yet
  • That’s what we are going to do today

Extracting From Strings

  • We can extract an individual character from a string using square brackets
  • This allows us to specify the index of the character we want to extract
  • Note that the index of the first character is 0
  • For example take the string “silksong”, the index of each character are as follows:
s i l k s o n g
0 1 2 3 4 5 6 7

Extracting From Strings

We can then extract the first character from a string as follows:

s = "silksong"
first_char = s[0]
print(first_char)

Visualize

Extracting From Strings

We can extract multiple characters if we want to:

s = "silksong"
first_char = s[0]
second_char = s[1]
third_char = s[2]
print(first_char, second_char, third_char)

Visualize

Length of String

You can get the length of a string using the len() function:

s = "silksong"
print(len(s))

Visualize

Slicing a String

  • It is possible to extract multiple characters from a string using slicing
  • slicing allows you to specify multiple indexes you would like to extract
  • The syntax for this, given some string s, is:
s[<<firstIndex>>:<<secondIndex>>]

Note that the <<secondIndex>> is exclusive

Slice Example

For example, we can extract the second through fifth characters with the following code:

s = "silksong"
second_to_fifth = s[1:5]
print(second_to_fifth)

Visualize

Another Slice Example

What happens if the <<firstIndex>> and <<secondIndex>> are the same? Or if the <<secondIndex>> is less than the <<firstIndex>>?

Let’s try it and see:

s = "silksong"
same = s[1:1]
less = s[2:1]
print(same, less)

Visualize

Nothing is extracted! The result is empty!

Combining Strings

You can combine two strings using the + operator:

s1 = "silk"
s2 = "song"
s = s1 + s2
print(s)

Visualize

Looping Over Strings

  • Recall, that there are two main loop constructs in python, while and for
  • We can use either to loop over strings

Here is how we could do it using while:

s = "silksong"
i = 0
while i < len(s):
    print(s[i])
    i += 1

Visualize

Looping Over Strings

Here is how we could do it using for and range:

s = "silksong"
for i in range(0, len(s)):
    print(s[i])

Visualize

Looping Over Strings

We can also use a for loop without range:

s = "silksong"
for c in s:
    print(c)

Visualize