Sitemap

Python — Strings (Part 2)

1 min readFeb 23, 2025

--

Slicing

You can return a range of characters by using the slice syntax.

Get Sithila Sihan Somaratne’s stories in your inbox

Join Medium for free to get updates from this writer.

Specify the start index and the end index, separated by a colon, to return a part of the string.

s = "Hello, World!"
print(s[3:5]) # lo

The above code gets the characters from position 2 to position 5 (not included).

Note: The first character has index 0.

Slice From the Start

By leaving out the start index, the range will start at the first character:

s = "Hello, World!"
print(s[:5]) # Hello

The above code gets the characters from the start to position 5 (not included).

Slice To the End

By leaving out the end index, the range will go to the end:

s = "Hello, World!"
print(s[7:]) # World! (note, not " World!" that would be s[6:])

The above code gets the characters from position 2, and all the way to the end.

Negative Indexing

Use negative indexes to start the slice from the end of the string:

s = "Hello, World!"
print(s[-4:-2]) # rl

The above code gets the characters from: “r” in “World!” (position -4) to, but not included: “d” in “World!” (position -2).

--

--

Sithila Sihan Somaratne
Sithila Sihan Somaratne

Written by Sithila Sihan Somaratne

I'm a student. I love programming and I would like to become a Senior Software Engineer.