stringindicesprogram-slicing

Basic string slicing from indices


I will state the obvious that I am a beginner. I should also mention that I have been coding in Zybooks, which affects things. My textbook hasn't helped me much

I tried sub_lyric= rhyme_lyric[ : ]

Zybooks should be able to input an index number can get only that part of the sentence but my book doesnt explain how to do that. If it throws a [4:7] then it would output cow. Hopefully I have exolained everything well.

a screenshot of the problem


Solution

  • You need to set there:

    sub_lyric = rhyme_lyric[start_index:end_index]
    

    The string is as a sequence of characters and you can use string slicing to extract any sub-text from the main one. As you have observed:

    sub_lyric = rhyme_lyric[:]
    

    will copy the entire content of rhyme_lyric to sub_lyric.

    To select only a portion of the text, specify the start_index (strings start with index 0) to end_index (not included).

    sub_lyric = rhyme_lyric[4:7]
    

    will extract characters in rhyme_lyric from position 4 (included) to position 7 (not included) so the result will be cow.

    You can check more on string slicing here: Python 3 introduction