liveBook · Manning

Substring

As explained in Get Programming: Learn to code with Python

A substring is a contiguous sequence of characters extracted from a string.

A substring is part of a larger string. For example, "snap" is a substring of "snap crackle pop". Use substrings when you need just one part of a name, a line of data, or a piece of text. section 7.2 section 8.0

Take part of a string

Set cheer = "Python rules!". Then cheer[2:7] gives 'thon '. The 2 selects the first character to take; the 7 marks where to stop, but that character is not included. A slice can also include a step: cheer[2:11:3] gives 'tnu' by taking every third character. section 7.2

Once you have a string, you can also look for or change substrings:

  • Use find() to get the starting index of the first case-sensitive match, or -1 if there is no match. For example, "some_string".find("ing") gives 8. section 8.1
  • Use rfind() to locate the match nearest the end. You can also count occurrences or replace them. section 8.1 section 8.3
Listing 12.2. Storing the first and last names in variables
space = name1.find(" ")                              #1
name1_first = name1[0:space]                         #2
name1_last = name1[space+1:len(name1)]               #3
space = name2.find(" ")                              #4
name2_first = name2[0:space]                         #4
name2_last = name2[space+1:len(name2)]               #4

This name-mashup code finds the space in each full name, then slices before and after it. The resulting first and last names are saved separately for later use. section 12.2

Quick check: if name = "Aqua Man" and space = name.find(" "), what do name[0:space] and name[space+1:len(name)] give? They give 'Aqua' and 'Man'. Finding a boundary first makes the same slicing pattern useful for different names. section 12.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through slice bounds and steps, then explains find() and rfind() results.
Examples
Uses "Python rules!" slices, word searches, and full names split for a name-mashup program.
What it assumes
Introduces substring extraction after single-character indexing, then builds on strings and indices.
What you can do after
Build it from scratch: split input names into stored parts and combine them in a name-mashup program.
How it connects
Links string indexing and slicing to find(), rfind(), counting, replacement, and concatenation.

Also explained in

Compare how 5 books explain substring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.