6.2: Getting the length of a string using len

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    6.2: Getting the length of a string using len

    len is a built-in function that returns the number of characters in a string:

    >>> fruit = 'banana'
    >>> len(fruit)
    6

    To get the last letter of a string, you might be tempted to try something like this:

    >>> length = len(fruit)
    >>> last = fruit[length]
    IndexError: string index out of range

    The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:

    >>> last = fruit[length-1]
    >>> print(last)
    a

    Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.


    This page titled 6.2: Getting the length of a string using len was last modified on Tue, 01 Dec 2020 03:50:53 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.