String slicing

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

String indexing

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

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