Chapter 6. Strings
This chapter covers
- Understanding strings as sequences of characters
- Using basic string operations
- Inserting special characters and escape sequences
- Converting from objects to strings
- Formatting strings
- Using the byte type
Handling text—from user input to filenames to chunks of text to be processed—is a common chore in programming. Python comes with powerful tools to handle and format text. This chapter discusses the standard string and string-related operations in Python.
For the purposes of extracting characters and substrings, strings can be considered to be sequences of characters, which means that you can use index or slice notation:
One use for slice notation with strings is to chop the newline off the end of a string (usually, a line that’s just been read from a file):
This code is just an example. You should know that Python strings have other, better methods to strip unwanted characters, but this example illustrates the usefulness of slicing.
You can also determine how many characters are in the string by using the len function, just like finding out the number of elements in a list: