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.

6.1. Strings as sequences of characters

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:

>>> x = "Hello"
>>> x[0]
'H'
>>> x[-1]
'o'
>>> x[1:]
'ello'

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):

>>> x = "Goodbye\n"
>>> x = x[:-1]
>>> x
'Goodbye'

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:

>>> len("Goodbye")
7

6.2. Basic string operations

6.3. Special characters and escape sequences

6.4. String methods

6.5. Converting from objects to strings

6.6. Using the format method

6.7. Formatting strings with %

6.8. String interpolation

6.9. Bytes

Summary

sitemap