Python - Slicing Strings

Slicing

You can return a range of characters from a string using slicing syntax. To do this, specify the start index and the end index, separated by a colon, to extract a portion of the string.

Example

Get the characters from position 2 to position 5 (not included):

b = "Kathmandu, the capital of Nepal"
print(b[2:5])

Output:

thm

Slice From the Start

By leaving out the start index, the slice will begin at the first character.

Example

Get the characters from the start to position 5 (not included):

b = "Pokhara, known for its stunning lakes"
print(b[:5])

Output:

Pokha

Slice To the End

By leaving out the end index, the slice will continue to the end of the string.

Example

Get the characters from position 2, all the way to the end:

b = "Bhaktapur, famous for its rich culture"
print(b[2:])

Output:

aktapur, famous for its rich culture

Negative Indexing

You can also use negative indexes to start the slice from the end of the string.

Example

Get the characters:
From: "c" in "culture" (position -7)
To, but not included: "e" in "culture" (position -1):

b = "Lumbini, the birthplace of Lord Buddha"
print(b[-7:-1])

Output:

cultu