Skip to main content
Engineering LibreTexts

8.2: String Slicing

  • Page ID
    117572
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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: String indexing
    Concepts in Practice \(\PageIndex{1}\): Accessing characters in a string using indexing

    Which character is at index 1 in the string "hello"?

    1. "h"
    2. "e"
    3. "o"
    Answer

    b. Since indexing starts from 0, the character at index 1 is the second character in the string, which is "e" .

    Concepts in Practice \(\PageIndex{2}\): Accessing characters in a string using indexing

    What is the character at index -2 in the string "Blue"?

    1. "e"
    2. "u"
    3. "l"
    Answer

    b. Since negative indexing starts from -1 from the right of the string to the left, "u" is at index -2.

    Concepts in Practice \(\PageIndex{3}\): Accessing characters in a string using indexing

    What is the output of the following code?

    word = "chance"
    print(word[-1] == word[5])
    
    1. True
    2. False
    Answer

    a. Character "e" in the string "chance" has index of -1 (negative indexing) and 5 (positive indexing).

    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 \(\PageIndex{4}\): Accessing characters in a string using indexing

    What is the output of the following code?

    a_string = "Hello world"
    print(a_string[2:4])
    
    1. "el"
    2. "ll"
    3. "llo"
    Answer

    b. a_string[2:4] is a slice including the third and fourth characters, which is "ll" .

    Concepts in Practice \(\PageIndex{5}\): Accessing characters in a string using indexing

    What is the output of the following code?

    location = "classroom"
    print(location[-3:-1])
    
    1. "ro"
    2. "oo"
    3. "oom"
    Answer

    b. The slice [-3:-1] includes characters at index -3 and -2, which are "oo" .

    Concepts in Practice \(\PageIndex{6}\): Accessing characters in a string using indexing

    What is the output of the following code?

    greeting = "hi Leila"
    name = greeting[3:]
    
    1. " Leila"
    2. "Leila"
    3. "ila"
    Answer

    b. The string slice of greeting[3:] is the substring starting from index 3 up to the end of the string, which is "Leila" .

    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
    Concepts in Practice \(\PageIndex{7}\): Modifying string content

    What is the correct way of replacing the first character in a string to character "*" in a new string?

    1. x = "string"
      x[0] = "*"
    x = "string"
    x = "*" + x[1:]
    
    x = "string"
    x = "*" + x
    Answer

    b. To modify string content, a new variable must be created with desired modifications.

    Concepts in Practice \(\PageIndex{8}\): Modifying string content

    What type of error will result from the following code?

    string_variable = "example"
    string_variable[-1] = ""
    
    1. TypeError
    2. IndexError
    3. NameError
    Answer

    a. Attempting to assign a value to an index or range of indexes in a string results in TypeError: 'str' object does not support item assignment.

    Concepts in Practice \(\PageIndex{9}\): Modifying string content

    What is the output of the following code?

    str = "morning"
    str = str[1]
    print(str)
    
    1. TypeError
    2. m
    3. o
    Answer

    c. The character at index 1, "o" , is replacing the content of variable str . As such, the print statement prints "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.

    Interactive Code
     
     
    Answer

    greeting = "Hello my fellow classmates"
    print(greeting[:5])
    print("Hi" + greeting[5:])

    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
    Interactive Code
    string_variable = "testet"
    indices = [0, 1, 3]
    
    
     
    Answer

    string_variable = "testet"
    indices = [0, 1, 3]

    for i in indices:
    string_variable = string_variable[:i] + '*' + string_variable[i+1:]

    out = ""
    for i in string_variable:
    if i != '*':
    out += i

    print(out)


    This page titled 8.2: String Slicing is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.