Chapter 7

Strings and Text Processing

A string is a sequence of characters. Once you see it that way, indexing, slicing, searching, and transforming text all get much easier.

Chapter 7, Strings and Text Processing

What you will learn

  • Index and slice strings.
  • Use common string methods.
  • Understand that strings are immutable.
  • Use split() and join() to move between text and lists.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

7.1 Indexing and Slicing

Type this into a file, predict the output, then run it.

Python
word = "Python"
print(word[0])
print(word[-1])
print(word[1:4])
print(word[::-1])
print(word[1:])
print(word[:2])

TPRM Lab 7.1: Strings Are Immutable

Type this into a file, predict the output, then run it.

Python
word = "Python"
print(word[0])
# word[0] = "J"

7.2 Useful String Methods

Type this into a file, predict the output, then run it.

Python
text = "  Python Is Fun  "
print(text.strip())
print(text.lower())
print(text.upper())
print(text.replace("Fun", "Useful"))

7.3 split() Produces a List

Type this into a file, predict the output, then run it.

Python
colors = "red,green,blue"
parts = colors.split(",")
print(parts)
print(" | ".join(parts))
print("".join(parts))

TPRM Lab 7.3: Split Text into Pieces

Type this into a file, predict the output, then run it.

Python
name = "John Smith"
parts = name.split()

print(parts)
print(type(parts))
print(parts[0])

Back to Python the TPRM Way