Link Search Menu Expand Document

Strings

Table of contents

  1. Description
  2. Example
  3. Indexing
  4. Slicing
  5. Immutability
  6. Instructional Video

Description

Strings are simply a sequence of characters, enclosed by quotes.

  • Immutable: you cannot change the values of their individual characters.
  • Index numbers allow access to individual characters.
  • Ordered: The characters are stored in a specific order.
  • Many different actions (methods and functions) can be performed on strings.
  • Python Docs: Strings, Text Sequence Type

Example

Indexing

An index is the position of an element in a sequence. Indexing begins at 0 with the first element. Negative indexing begins at -1 with the last element.

Slicing

A slice is a piece of a string. It is defined by a starting index, a (non-inclusive) ending index, and a step value. If any of the three arguments to the slice are missing, the defaults are as follows:

  • Start: first character
  • End: last character
  • Step: 1
Start End + 1 Step Code Result
3 9   flavor[3:9] ‘ten La’
  6   flavor[:6] ‘Molten’
7     flavor[7:] ‘Lava’
      flavor[:] ‘Molten Lava’
-1   -1 flavor[-1::-1] ‘avaL netloM’
    2 flavor[::2] ‘Mle aa’

Run on repl.it

Immutability

Strings are immutable. This means once you instantiate them, you can’t change their attributes.

  1. Run the program as-is, with line 5 commented out. Notice the error in the console:
    • 'str' object does not support item assignment.
  2. Next, comment out line 4, and uncomment line 5. The program will run without any errors.

So, you can reassign an entire string, but you cannot reassign parts (individual elements) of a string.

Instructional Video