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 of first[0]. Index 1 is the second character. The first character is always at index 0.
  • Using first[0:1] (a slice) instead of first[0] (a single character). Both produce the same result, but first[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, but in is 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-noon

Python'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 modify message in 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))   # 11

Since -3 counts from the end, word[-3:] gives the last three letters of any word — no counting required.

Common mistakes.

  • Writing word[-3] instead of word[-3:]. A single index returns one character; a slice with : returns a substring of the specified length.
  • word[len(word) - 3:] also works, but word[-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.