Skip to ContentGo to accessibility page

8.2 String slicing

Learning objectives

By the end of this section you should be able to

  • Use string indexing to access characters in the string.
  • Use string slicing to get a substring from a string.
  • Identify immutability characteristics of strings.

String indexing

A string is a type of sequence. A string is made up of a sequence of characters indexed from left to right, starting at 0. For a string variable s, the left-most character is indexed 0 and the right-most character is indexed len(s) - 1. Ex: The length of the string "Cloud" is 5, so the last index is 4.

Negative indexing can also be used to refer to characters from right to left starting at -1. For a string variable s, the left-most character is indexed -len(s) and the right-most character is indexed -1. Ex: The length of the string "flower" is 6, so the index of the first character with negative indexing is -6.

Checkpoint

Concepts in Practice

Accessing characters in a string using indexing

1.
Which character is at index 1 in the string "hello"?
  1. "h"
  2. "e"
  3. "o"
2.
What is the character at index -2 in the string "Blue"?
  1. "e"
  2. "u"
  3. "l"
3.
What is the output of the following code?
word = "chance"
print(word[-1] == word[5])
  1. True
  2. False

String slicing

String slicing is used when a programmer must get access to a sequence of characters. Here, a string slicing operator can be used. When [a:b] is used with the name of a string variable, a sequence of characters starting from index a (inclusive) up to index b (exclusive) is returned. Both a and b are optional. If a or b are not provided, the default values are 0 and len(string), respectively.

Example 8.2

Getting the minutes

Consider a time value is given as "hh:mm" with "hh" representing the hour and "mm" representing the minutes. To retrieve only the string's minutes portion, the following code can be used:

    time_string = "13:46"
    minutes = time_string[3:5]
    print(minutes)

The above code's output is:

    46

Example 8.3

Getting the hour

Consider a time value is given as "hh:mm" with "hh" representing the hour and "mm" representing the minutes. To retrieve only the string's hour portion, the following code can be used:

    time_string = "14:50"
    hour = time_string[:2]
    print(hour)

The above code's output is:

    14

Concepts in Practice

Getting a substring using string slicing

4.
What is the output of the following code?
a_string = "Hello world"
print(a_string[2:4])
  1. "el"
  2. "ll"
  3. "llo"
5.
What is the output of the following code?
location = "classroom"
print(location[-3:-1])
  1. "ro"
  2. "oo"
  3. "oom"
6.
What is the output of the following code?
greeting = "hi Leila"
name = greeting[3:]
  1. " Leila"
  2. "Leila"
  3. "ila"

String immutability

String objects are immutable meaning that string objects cannot be modified or changed once created. Once a string object is created, the string's contents cannot be altered by directly modifying individual characters or elements within the string. Instead, to make changes to a string, a new string object with the desired changes is created, leaving the original string unchanged.

Checkpoint

Strings are immutable

Strings are immutable; ch 8, video 2

Concepts in Practice

Modifying string content

7.
What is the correct way of replacing the first character in a string to character "*" in a new string?
  1. x = "string"
    x[0] = "*"
    
  2. x = "string"
    x = "*" + x[1:]
    
  3. x = "string"
    x = "*" + x
    
8.
What type of error will result from the following code?
string_variable = "example"
string_variable[-1] = ""
  1. TypeError
  2. IndexError
  3. NameError
9.
What is the output of the following code?
str = "morning"
str = str[1]
print(str)
  1. TypeError
  2. m
  3. o

Try It

Changing the greeting message

Given the string "Hello my fellow classmates" containing a greeting message, print the first word by getting the beginning of the string up to (and including) the 5th character. Change the first word in the string to "Hi" instead of "hello" and print the greeting message again.

Try It

Editing the string at specified locations

Given a string variable, string_variable, and a list of indexes, remove characters at the specified indexes and print the resulting string.

    Input:
    string_variable = "great"
    indices = [0, 1]
    Prints: 
    eat
Citation/Attribution
Reuse and redistribution of this content in digital or print format:
  • This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's prior written permission.
  • This book uses the Creative Commons Attribution-NonCommercial-ShareAlike License, which means that you can reuse and modify the material only for noncommercial purposes, must attribute OpenStax, and must distribute any derivative works under the same license.
  • Any commercial printing of this textbook, including using a local or custom printer, must be approved by OpenStax, and proper citation provided.
  • OpenStax-copyrighted images, activities, assessments, and similar components of this book are subject to the same licensing – CC-BY-NC-SA. They can be used for noncommercial purposes with attribution. Commercial use requires permission.
  • Permission requests: Anyone who intends to incorporate this content (including text, images, and other components) into large language models, use it in AI offerings, use it commercially (including in print), and/or has questions about another use case is welcome to complete our reuse request form.
Attribution information
  • If you are redistributing all or part of this book in a noncommercial print format, then you must include on every physical page the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

  • If you are redistributing all or part of this book in a noncommercial digital format, then for every page that includes OpenStax content, you must license the derivative work under the same CC-BY-NC-SA license as the original, and include on every digital page view the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

Citation information

The information below includes the information needed to generate citations in most major styles (APA, MLA, etc.); you must reformat and organize the information as needed to fit the requirements of the style. Use the information below to generate a citation. We recommend using a citation tool such as this one.

© Apr 23, 2026 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike License. The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo, and Rice University name, and Rice University logo trademarks, or wordmarks are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.