14. Working with text — Homework solutions
The .py solution files are in
exercises/14/homework/solutions/.
Problem 1 — Initials
Problem. Print initials like K.R. from
first and last names.
How to think about it. A name's first letter is
name[0] (index zero, because Python is 0-indexed). Join
with f-strings and dots.
Worked solution.
first = "Keiko"
last = "Raharja"
print(f"{first[0]}.{last[0]}.")Output:
K.R.
Common mistakes.
- Using
first[1]instead offirst[0]. Index1is the second character. The first character is always at index0. - Using
first[0:1](a slice) instead offirst[0](a single character). Both produce the same result, butfirst[0]is simpler.
Problem 2 — Contains
Problem. Print yes or no
for whether a sentence holds python.
How to think about it. The in operator
returns True when the substring is found, which pairs
directly with if.
Worked solution.
sentence = "i am learning python this year"
if "python" in sentence:
print("yes")
else:
print("no")Common mistakes.
- Using
.find()and checking!= -1. That works, butinis clearer when you only need to know whether the word is present.
Problem 3 — Censor
Problem. Replace every space with a dash.
Worked solution.
message = "meet me at noon"
dashed = message.replace(" ", "-")
print(dashed) # meet-me-at-noonPython's .replace() returns only the new string, not a
second count value. No extra step needed to keep just the string.
Common mistakes.
- Expecting
.replace()to modifymessagein place. String methods in Python never modify the original; they always return a new string. Store the result in a variable to use it.
Challenge — Last word length
Problem. Print the last three characters with a
negative slice, and the length with len().
Worked solution.
word = "programming"
print(word[-3:]) # ing
print(len(word)) # 11Since -3 counts from the end, word[-3:]
gives the last three letters of any word — no counting
required.
Common mistakes.
- Writing
word[-3]instead ofword[-3:]. A single index returns one character; a slice with:returns a substring of the specified length. word[len(word) - 3:]also works, butword[-3:]is shorter and clearer: "three from the end".
Done?
You can now slice, search, and replace text. Part 3's last chapter — Getting input — lets users type values, arriving as strings to slice and check.