Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Slices

You can read one character of a text by its index: word[0]. With a slice, you read a whole part of it at once. In the square brackets, write two indexes with a colon between them: where the part starts and where it stops.

word = "Python"
print(word[0:4])
print(word[2:5])

This prints:

Pyth
tho

The character at the stop index is not included, just as range(0, 4) stops at 3. word[0:4] gives the characters at indexes 0, 1, 2 and 3: four characters. That's handy, because the stop minus the start is the length of the slice.

You can leave out either index. Without the start, the slice starts at the beginning; without the stop, it goes to the end. And negative indexes count from the end, as you know:

word = "Python"
print(word[:3])
print(word[2:])
print(word[-3:])

This prints:

Pyt
thon
hon

word[:3] is the first three characters, word[2:] everything from index 2 on, and word[-3:] the last three characters.

Slices work on lists too, and they give a new list. When a list of scores is in order from the best, its top three are scores[:3]:

scores = [98, 91, 85, 77, 60]
print(scores[:3])
print(scores[-2:])

This prints:

[98, 91, 85]
[77, 60]

Unlike a single index, a slice never ends with an IndexError. If it reaches past the end, you simply get what there is: "Hi"[:10] is "Hi", and [98, 91][:3] is [98, 91]. So scores[:3] works even when there are fewer than three scores.

And like the methods in this lesson, a slice doesn't change the original. It returns a new text or a new list.

Instructions

  1. 1

    The variable date holds a date written as year-month-day. Use slices to print it the way it's written in the United States, month/day/year: 11/26/2026. Keep the lines with date and scores: the exercise also tries other values in them.

  2. 2

    The list scores holds the best scores of a game, from the best. Print the top three: [98, 91, 85].

Back

9/12

  1. 1. Upper and Lower Case
  2. 2. Trimming Spaces
  3. 3. Replacing Text
  4. 4. Quiz: Text Methods
  5. 5. Searching in Text
  6. 6. Beginnings and Ends
  7. 7. Splitting Text
  8. 8. Joining a List
  9. 9. Slices
  10. 10. Quiz: Slices
  11. 11. Decimal Places
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.