8.2 String slicing

3 min readjune 24, 2024

Strings in Python are sequences of characters with powerful and capabilities. You can access individual characters using positive or , starting from 0 or -1 respectively. This allows for precise character retrieval within strings.

Slicing lets you extract substrings by specifying start, end, and step values. It's a versatile tool for manipulating strings, from basic to advanced operations like reversing. Remember, strings are immutable, so operations create new objects.

String Indexing and Slicing

String character indexing

Top images from around the web for String character indexing
Top images from around the web for String character indexing
  • Strings consist of a of individual characters
    • Each character occupies a specific position within the string called its index
    • String indexing begins at 0 for the first character and increments by 1 for each subsequent character
    • The index of the last character equals the length of the string minus 1 (
      len(string) - 1
      )
  • Access individual characters using positive indexing
    • Syntax:
      [string[index]](https://www.fiveableKeyTerm:string[index])
    • Retrieves the character at the specified index position
    • "Hello"[0] yields "H" (the character at index 0)
  • Access individual characters using negative indexing
    • Counts backwards from the end of the string
    • -1 refers to the last character, -2 the second-to-last, and so on
    • "Hello"[-1] yields "o" (the last character)

Substring extraction with slicing

  • Slicing extracts a portion of a string and returns it as a new string ( extraction)
  • Slicing syntax:
    [string[start:end:step]](https://www.fiveableKeyTerm:string[start:end:step])
    • start
      : The index at which to begin the slice (inclusive), defaults to 0 if not provided
    • end
      : The index at which to end the slice (exclusive), defaults to the length of the string if not provided
    • step
      : The or interval between characters to include, defaults to 1 if not provided
  • Slicing with positive indexes
    • "Hello"[1:4] yields "ell" (characters from index 1 up to, but not including, index 4)
    • "Hello"[1:] yields "ello" (characters from index 1 to the end of the string)
    • "Hello"[:3] yields "Hel" (characters from the beginning of the string up to, but not including, index 3)
  • Slicing with negative indexes
    • "Hello"[-4:-1] yields "ell" (characters from the fourth-to-last index up to, but not including, the last index)
    • "Hello"[:-2] yields "Hel" (characters from the beginning of the string up to, but not including, the second-to-last index)
    • "Hello"[-3:] yields "llo" (characters from the third-to-last index to the end of the string)
  • Slicing with a step
    • "Hello"[0:5:2] yields "Hlo" (every second character from index 0 to 5)
    • "Hello"[::2] yields "Hlo" (every second character from the beginning to the end of the string)
    • "Hello"[::-1] yields "olleH" (reverses the order of the characters in the string)

Immutability of strings

  • Strings are immutable data types in Python
    • Once a string is created, its contents cannot be altered
    • Operations that appear to modify a string actually return a new string object
  • Assigning a new value to a specific index position is not permitted
    • "Hello"[0] = "J" raises a
      TypeError
      because strings do not support item assignment
  • Concatenating strings using the
    +
    operator creates a new string
    • "Hello" + " World" returns a new string "Hello World"
  • Slicing a string returns a new string containing the extracted substring
    • "Hello"[1:4] returns a new string "ell"
  • To modify a string, create a new string with the desired changes
    • "Hello".replace("H", "J")
      returns a new string "Jello"

String operations and concepts

  • Strings are sequences of characters, allowing for various operations
  • Indexing is used to access individual characters within a string
  • Slicing is a technique for extracting substrings from a string
  • The stride in slicing determines the step size between characters

Key Terms to Review (21)

[::]: [::] is a slicing notation used in Python to access and manipulate sequences like strings, lists, and tuples. This notation allows you to specify a start point, an endpoint, and a step value in a very concise way. By default, if you omit the start and end values, Python will slice the entire sequence while the step value controls the increments of indices, making it a powerful tool for accessing parts of a sequence efficiently.
Colon Operator: The colon operator is a powerful tool in Python used primarily for string slicing, enabling you to extract specific portions of strings by specifying a start and end index. It allows for flexible manipulation of strings by accessing sub-parts without needing additional functions. Understanding how the colon operator works is essential for efficiently handling string data and performing operations like extracting, modifying, or analyzing text.
End index: The end index is a key component in string slicing that indicates the position where the slice should stop, meaning it determines the point at which characters will no longer be included in the resulting substring. It is important to note that the character at this index is not included in the final output, allowing for precise control over which part of the string is extracted. Understanding the end index helps users manipulate strings efficiently and accurately.
Escape sequence: An escape sequence is a series of characters used to represent special characters in a string. It typically begins with a backslash followed by one or more characters.
Immutability: Immutability refers to the property of an object or a variable where its value cannot be changed or modified once it has been created. This concept is fundamental in programming and has important implications in various contexts, including string operations, tuple handling, and dictionary management.
Indexing: Indexing is the process of accessing specific elements within a data structure, such as a string, list, or array, by their position or index. It allows for the retrieval, manipulation, and identification of individual components within a larger collection of data.
List: A list in Python is an ordered collection of items, where each item can be of a different data type. Lists are one of the most fundamental and versatile data structures in the Python programming language, allowing you to store and manipulate multiple values in a single variable.
Negative Indexing: Negative indexing refers to the ability to access elements in a sequence, such as a string or list, by specifying a negative index value. This allows you to count from the end of the sequence instead of the beginning, making it a useful tool for string slicing and other data manipulation tasks.
Sequence: A sequence is an ordered arrangement of elements, such as numbers, letters, or objects, that follow a specific pattern or order. This concept is fundamental in various areas of computer science and mathematics, including programming, data structures, and algorithms.
Slice(): The slice() method in Python is a powerful tool for extracting a subset of characters from a string. It allows you to create a new string by selecting a range of characters from the original string, without modifying the original.
Slicing: Slicing is a fundamental operation in Python that allows you to extract a subset of elements from a sequence, such as a string, list, or other iterable data structures. It provides a powerful way to access and manipulate data by specifying the start, stop, and step of the desired subset.
Start Index: The start index refers to the position or location within a string where a substring or slice begins. It is a fundamental concept in string slicing, which allows you to extract a portion of a string based on specified starting and ending positions.
Step Value: The step value is a parameter used in string slicing that determines the increment or decrement of the index when selecting a subset of characters from a string. It specifies the number of positions to move between each selected character.
Stride: Stride refers to the distance covered in a single step or the length of a single step taken during a movement or action. It is a fundamental concept in the context of string slicing, where it determines the spacing between the extracted characters or substrings.
String: A string is a sequence of characters, such as letters, numbers, and symbols, that is used to represent and store textual data in programming. Strings are a fundamental data type in many programming languages, including Python, and are essential for tasks such as text manipulation, data storage, and communication.
String[index]: The string[index] notation is a way to access individual characters within a string. It allows you to retrieve a specific character from a string by specifying its position or index within the string.
String[start:end:step]: The string[start:end:step] notation is a way to extract a substring from a larger string in Python. It allows you to specify the starting index, ending index, and step size to select a specific portion of the string.
Strip(): The strip() method in Python is used to remove any leading or trailing whitespace characters, such as spaces, tabs, or newlines, from a string. It is a powerful tool for cleaning and formatting string data, ensuring consistent formatting across different inputs.
Substring: A substring is a contiguous sequence of characters within a larger string. It represents a portion or a part of the original string, allowing for the extraction and manipulation of specific sections of text.
Substring Extraction: Substring extraction is the process of extracting a portion or segment of a string, known as a substring, from the original string. This technique is a fundamental operation in string manipulation and is commonly used in various programming tasks.
Zero-Based Indexing: Zero-based indexing is a method of counting elements in a data structure, such as a string or an array, where the first element is assigned the index of 0 instead of 1. This approach allows for more efficient and intuitive manipulation of data by aligning the index with the actual position of the element.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.