Practice makes perfect 7/15


Below is the solution given by codecademy. My question is on line 5 about text[l]. Isn’t text a string? I know that you can specify the position of an item in a list, but how can you specify a letter in a string? Thanks.

def reverse(text):
    word = ""
    l = len(text) - 1
    while l >= 0:
        word = word + text[l]
        l -= 1
    return word


A string is iterable, meaning it has an index that starts at 0 and goes up to the string length minus 1 (because of zero-indexing).

In Python, the first character of a string is at index 0

my_string = "some characters in a string"

my_string[0]                     # ->  's'

The last character may be found in one of two ways, via the index,

my_string[len(my_string) - 1]    # ->  'g'

or by negative indexing,

my_string[-1]                    # ->  'g'

The negative sign tells Python to start on the right side and count to the left starting outside the string. -1 is the first index from the right. By this we can conclude that the first character, negative indexed would be,

my_string[-len(my_string)]       # ->  's'


Thank you so much for clarifying that. I was trying to figure out why i needed to do len(string)-1 but that makes perfect sense now. Thanks!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.