String Basics: Indexing, Slicing, and Substrings Quiz Quiz

Explore key concepts of string manipulation, including indexing, slicing, and extracting substrings. This quiz is designed to enhance your understanding of how to access, modify, and analyze strings effectively using common operations.

  1. Accessing Characters in a String

    Given the string message = 'Adventure', what character does message[3] return?

    1. d
    2. v
    3. n
    4. e

    Explanation: String indexing in most programming languages starts from zero, so message[3] refers to the fourth character. In 'Adventure', the fourth character is 'e'. The option 'd' represents the second character, 'v' is the third, and 'n' is the fifth, making them incorrect.

  2. Negative Indexing

    If text = 'Unicorn', what is the result of text[-2]?

    1. r
    2. o
    3. c
    4. n

    Explanation: Negative indexing counts from the end of the string; text[-1] is the last character, so text[-2] is 'r'. The option 'o' is text[-3], 'n' is the last character, and 'c' is in the middle, so those are not the correct answer.

  3. String Slicing Syntax

    Given s = 'Notebook', what is produced by s[1:5]?

    1. otebo
    2. Noteb
    3. oteb
    4. Note

    Explanation: The slicing s[1:5] starts at index 1 and goes up to, but does not include, index 5. That produces 'oteb'. 'Note' and 'Noteb' start at the wrong index, while 'otebo' includes one extra character beyond the slice.

  4. Extracting Substrings

    Given 'Rainbow', which slice extracts 'bow'?

    1. word[3:6]
    2. word[5:8]
    3. word[4:7]
    4. word[6:9]

    Explanation: In 'Rainbow', 'b' is at index 4, so word[4:7] captures 'b', 'o', 'w'. 'word[5:8]' goes past the end, 'word[3:6]' gives 'nbo', and 'word[6:9]' exceeds the string's length, returning only 'w' in some languages or causing an error.

  5. Checking for Substring Existence

    For phrase = 'happy coding', which option checks if 'code' is a substring of phrase?

    1. phrase.has('code')
    2. 'code' in phrase
    3. phrase.check('code')
    4. phrase.finds('code')

    Explanation: The correct way to check for a substring is using the 'in' keyword: 'code' in phrase. The other options, like has(), check(), or finds(), are not standard string methods and would result in errors or undefined behavior.