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




