Overview

3 Strings

Strings are presented as the core way Python handles text—ranging from single characters to entire files. Two properties define them: they are immutable and, in Python 3, they represent Unicode text. Because strings are sequences, you can iterate through them, index into them, slice out parts, and use membership tests to search within them. The chapter also clarifies that Python has no separate character type (a one-character string fills that role) and underscores why immutability matters for correctness, efficiency, and safe use as dictionary keys, while distinguishing immutability from the idea of constants.

Through hands-on practice, the chapter develops fluency with everyday string techniques. A Pig Latin translator highlights concise membership checks, simple branching, and slicing to rearrange characters. Expanding to multiple words emphasizes splitting text into tokens, processing each element in a loop, and reassembling results. A key performance habit is to accumulate pieces in a list and combine them with join, rather than repeatedly concatenating strings, which is costly due to immutability.

Further exercises deepen per-character reasoning and transformation. An Ubbi Dubbi converter shows how to scan a word and conditionally insert fragments while safely building output, and a string-sorting task demonstrates combining sorted with join to create new strings from existing content. Throughout, the chapter reinforces practical patterns—split, join, slicing, membership tests, and sorted—along with thoughtful extensions like handling capitalization and punctuation, working with log files, and performing simple encodings. The result is a compact toolkit for reliable, efficient text manipulation in Python.

Summary

Python programmers are constantly dealing with text. Whether it’s because we’re reading from files, displaying things on the screen, or just using dicts, strings are a data type with which we’re likely familiar from other languages.

At the same time, strings in Python are unusual, in that they’re also sequences—​and thus, thinking in Python requires that you consider their sequence-like qualities. This means searching (using in), sorting (using sorted), and using slices. It also means thinking about how you can turn strings into lists (using str.split) and turn sequences back into strings (using str.join). While these might seem like simple tasks, they crop up on a regular basis in production Python code. The fact that these data structures and methods are written in C, and have been around for many years, means they’re also highly efficient—​and not worth reinventing.

FAQ

Why are Python strings immutable, and what does that imply for my code?Strings cannot be changed in place. Any “modification” produces a new string object. For example, s[0] = '!' raises a TypeError. Implications: - Methods like replace, upper, strip return new strings. - String concatenation with += creates new objects repeatedly (costly in loops). - Immutability enables safe use as dict keys and simpler reasoning in concurrent code.
How does Python 3 represent text, and what’s the difference between Unicode and UTF-8?Python 3 strings hold Unicode characters (abstract code points). UTF-8 is a variable-length byte encoding used to store/transmit those characters. When reading/writing files or network data, you convert between str and bytes via encode (str → bytes) and decode (bytes → str).
Is there a separate “character” type in Python?No. A “character” is just a one-character string. For example, len('a') == 1 and 'hello'[0] returns the string 'h'.
How do slices work on strings?Slices use s[start:stop:step] and return a new string: - Stop is exclusive (not included). - Step is optional (defaults to 1). Examples:
s = 'abcdefgh'
s[2:6]   # 'cdef'
s[2:6:2] # 'ce'
s[::2]   # 'aceg'
You can omit start or stop to go from the beginning or to the end.
What does the in operator do on strings and other collections?It checks membership by iterating: - 'a' in 'abcd' → True (searches characters). - On lists/tuples, it searches elements. - On dicts, it checks keys only (not values).
What’s the difference between str.split() and str.split(' ')?str.split() with no argument splits on any run of whitespace (spaces, tabs, newlines) and collapses multiple spaces. str.split(' ') splits only on a single space and preserves empty fields. Example:
s = 'abc  def  ghi'
s.split(' ')  # ['abc', '', 'def', '', 'ghi']
s.split()     # ['abc', 'def', 'ghi']
Why should I prefer list append + join over += when building strings?Because strings are immutable, s += piece creates a new string each iteration, which is slower and uses more memory. It’s more efficient to:
parts = []
for piece in pieces:
    parts.append(piece)
result = ''.join(parts)  # or ' '.join(parts)
What’s a simple way to implement Pig Latin in Python?Rules: if a word starts with a vowel, add 'way'; otherwise, move the first letter to the end and add 'ay'. Example (assumes lowercase, no punctuation):
def pig_latin(word):
    if word and word[0] in 'aeiou':
        return f'{word}way'
    return f'{word[1:]}{word[0]}ay'
How can I translate a word into Ubbi Dubbi?Prefix 'ub' before every vowel. Iterate character by character and build a list:
def ubbi_dubbi(word):
    out = []
    for ch in word:
        if ch in 'aeiou':
            out.append('ub' + ch)
        else:
            out.append(ch)
    return ''.join(out)
Assumes lowercase and no punctuation.
How do I sort the characters in a string?Use sorted to get a list of characters, then join:
def strsort(s):
    return ''.join(sorted(s))  # Unicode code point order

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Python Workout, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Python Workout, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Python Workout, Second Edition ebook for free