What you will learn
- Index and slice strings.
- Use common string methods.
- Understand that strings are immutable.
- Use
split()andjoin()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.
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.
word = "Python"
print(word[0])
# word[0] = "J"
7.2 Useful String Methods
Type this into a file, predict the output, then run it.
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.
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.
name = "John Smith"
parts = name.split()
print(parts)
print(type(parts))
print(parts[0])