Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Negative Indexing and String Length in Python | Variabler og Typer i Python
Introduksjon til Python
course content

Kursinnhold

Introduksjon til Python

Introduksjon til Python

1. Første Bekjentskap med Python
2. Variabler og Typer i Python
3. Betingelsesuttrykk i Python
4. Andre Datatyper i Python
5. Løkker i Python
6. Funksjoner i Python

book
Negative Indexing and String Length in Python

Negative indexing in Python allows you to access elements from the end. Instead of starting from the beginning (index 0), negative indexing starts from the end (index -1), which represents the last element.

12345
# The string of digits word = "codefinity" # Access the characters at index -1 and -9 (first and last ones) print(word[-1], word[-10])
copy

Note

Keep in mind that -1 is the go-to way to access the last element.

Now that you're familiar with referencing characters in a string, you might wonder how to determine the total number of characters in that string. Fortunately, Python provides the len() function for that. Just pass the string or the variable holding the string as an argument.

12345
# Initial string site = "codefinity" # Get the string length print(len(site))
copy

As you might notice, the length of a string corresponds to the number of characters in it. Thus, the total count of characters in a string is always one greater than the index of its last character. For instance, if the length of a string is 10, the index of its last character is 9.

Note

You can also determine the index of the last character by using len(string) - 1.

question mark

For the string test provided below, identify the character at index -4.

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 8
Vi beklager at noe gikk galt. Hva skjedde?
some-alt