Skip to main content

Chapter 8 - Strings and Text Editing (Python)

Here's a concise walkthrough of the main ideas in Chapter 8, each with a small example.


String literals and escape sequences

You can write strings with single or double quotes, and use backslash escape sequences like \', \", \n, \t, and \\ for special characters.

Example:

spam = "That is Alice's cat."
spam2 = 'Say hi to Bob\'s mother.'
print("Hello there!\nHow are you?\nI\'m doing fine.")

Raw strings

Prefix with r to make a raw string, where backslashes are not treated as escapes; useful for paths and regex patterns.

Example:

print(r'The file is in C:\Users\Alice\Desktop')
print(r'Hello...\n\n...world!') # backslashes shown literally

Multiline strings and comments

Triple quotes (''' or """) create multiline strings that can contain quotes and newlines; they're also often used as multiline comments or docstrings.

Example:

print('''Dear Alice,

Can you feed Eve's cat this weekend?

Sincerely,
Bob''')

"""This is a test program.
Written by Alice.
This can serve as a multiline comment or docstring."""

String indexing and slicing

Strings support indexing and slicing like lists; indexes start at 0, negative indexes count from the end, and slices use [start:end] with end excluded.

Example:

greeting = 'Hello, world!'
print(greeting[0]) # 'H'
print(greeting[-1]) # '!'
print(greeting[0:5]) # 'Hello'
print(greeting[7:-1]) # 'world'
print(greeting[7:]) # 'world!'

in and not in with strings

You can test if a substring appears inside another string using in / not in.

Example:

print('Hello' in 'Hello, world')      # True
print('HELLO' in 'Hello, world') # False
print('cats' not in 'cats and dogs') # False

f-strings (formatted string literals)

Prefix a string with f and use {} to embed expressions directly, instead of manual concatenation.

Example:

name = 'Al'
age = 4000
print(f'My name is {name}. I am {age} years old.')
print(f'In ten years I will be {age + 10}')

Literal braces:

print(f'{{name}}')  # prints {name}

Older formatting: %s and str.format()

Before f-strings, %s interpolation and .format() were used to insert values into strings.

Example with %s:

name = 'Al'
age = 4000
print('My name is %s. I am %s years old.' % (name, age))

Example with format():

print('My name is {}. I am {} years old.'.format(name, age))
print('{1} years ago, {0} was born and named {0}.'.format(name, age))

Changing case: upper(), lower(), isupper(), islower()

upper() / lower() return new strings; isupper() / islower() check if the string has letters and all are in that case.

Example:

spam = 'Hello, world!'
print(spam.upper()) # 'HELLO, WORLD!'
print(spam.lower()) # 'hello, world!'
print('HELLO'.isupper()) # True
print('abc123'.islower()) # True

Case-insensitive check:

print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')

isX checks: isalpha(), isalnum(), isdecimal(), isspace(), istitle()

These methods return True/False depending on what characters the string contains and whether it's title-cased.

Example:

print('hello'.isalpha())          # True
print('hello123'.isalnum()) # True
print('123'.isdecimal()) # True
print(' '.isspace()) # True
print('This Is Title Case'.istitle()) # True

Simple input validation:

while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Please enter a number for your age.')

while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers.')

startswith() and endswith()

Check if a string begins or ends with a given substring.

Example:

s = 'Hello, world!'
print(s.startswith('Hello')) # True
print(s.endswith('world!')) # True
print('abc123'.startswith('abc')) # True

Joining and splitting strings

  • 'sep'.join(list_of_strings) builds one string from many.
  • 'text'.split() splits into words on whitespace by default, or on a given delimiter.

Examples:

print(', '.join(['cats', 'rats', 'bats']))  # 'cats, rats, bats'
print(' '.join(['My', 'name', 'is', 'Simon'])) # 'My name is Simon'

print('My name is Simon'.split()) # ['My', 'name', 'is', 'Simon']
print('MyABCnameABCisABCSimon'.split('ABC')) # ['My', 'name', 'is', 'Simon']

Split multiline string into lines:

spam = '''Dear Alice,
There is a milk bottle in the fridge
that is labeled "Milk Experiment."

Please do not drink it.
Sincerely,
Bob'''
lines = spam.split('\n')

Justifying and centering text: rjust(), ljust(), center()

These methods pad strings to a given total width, optionally with a fill character.

Example:

print('Hello'.rjust(10))          # '     Hello'
print('Hello'.ljust(10, '-')) # 'Hello-----'
print('Hello'.center(20, '=')) # '=======Hello========'

Stripping whitespace or specific characters: strip(), lstrip(), rstrip()

Remove whitespace (default) or specified characters from the ends of a string.

Example:

spam = '   Hello, World   '
print(spam.strip()) # 'Hello, World'
print(spam.lstrip()) # 'Hello, World '
print(spam.rstrip()) # ' Hello, World'

Strip specific characters:

spam = 'SpamSpamBaconSpamEggsSpamSpam'
print(spam.strip('ampS')) # 'BaconSpamEggs'

Unicode code points: ord() and chr()

ord() gives the integer code point for a character; chr() does the reverse.

Example:

print(ord('A'))   # 65
print(ord('!')) # 33
print(chr(65)) # 'A'
print(chr(ord('A') + 1)) # 'B'

Clipboard access with pyperclip

The third-party pyperclip module provides copy() and paste() to interact with the system clipboard.

Example:

import pyperclip

pyperclip.copy('Hello, world!')
text = pyperclip.paste()
print(text) # 'Hello, world!'

Alternating-case program:

import pyperclip

text = pyperclip.paste()
alt_text = ''
make_upper = False

for ch in text:
alt_text += ch.upper() if make_upper else ch.lower()
make_upper = not make_upper

pyperclip.copy(alt_text)
print(alt_text)

Project: bulletPointAdder (add bullets to lines)

Reads text from clipboard, adds * to each line, writes back to clipboard using split('\n') and '\n'.join(...).

Core version:

import pyperclip

text = pyperclip.paste()
lines = text.split('\n')
for i in range(len(lines)):
lines[i] = '* ' + lines[i]
text = '\n'.join(lines)
pyperclip.copy(text)

Project: Pig Latin translator

Transforms each word into Pig Latin while preserving punctuation and capitalization using string methods like split, isalpha, isupper, istitle, lower, join.

Very compact sketch:

print('Enter the English message to translate into pig latin:')
message = input()
VOWELS = ('a', 'e', 'i', 'o', 'u', 'y')
pig_latin = []

for word in message.split():
prefix_non = ''
while len(word) > 0 and not word[0].isalpha():
prefix_non += word[0]
word = word[1:]
if len(word) == 0:
pig_latin.append(prefix_non)
continue

suffix_non = ''
while not word[-1].isalpha():
suffix_non = word[-1] + suffix_non
word = word[:-1]

was_upper = word.isupper()
was_title = word.istitle()
word = word.lower()

prefix_cons = ''
while len(word) > 0 and word[0] not in VOWELS:
prefix_cons += word[0]
word = word[1:]

if prefix_cons:
word = word + prefix_cons + 'ay'
else:
word = word + 'yay'

if was_upper:
word = word.upper()
elif was_title:
word = word.title()

pig_latin.append(prefix_non + word + suffix_non)

print(' '.join(pig_latin))

Overall idea of the chapter

Chapter 8 shows Python's rich set of string methods for searching, formatting, splitting, joining, and transforming text. F-strings are the modern way to embed values, and mastering these tools lets you process text data efficiently — from simple case conversion to full Pig Latin translation.