0% found this document useful (0 votes)
9 views2 pages

Python - Slicing Strings

The document explains how to slice strings in Python using slice syntax, which involves specifying a start and end index. It provides examples of slicing from the start, to the end, and using negative indexing to slice from the end of the string. Key examples include retrieving specific character ranges from the string 'Hello, World!'.

Uploaded by

vishal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Python - Slicing Strings

The document explains how to slice strings in Python using slice syntax, which involves specifying a start and end index. It provides examples of slicing from the start, to the end, and using negative indexing to slice from the end of the string. Key examples include retrieving specific character ranges from the string 'Hello, World!'.

Uploaded by

vishal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python - Slicing Strings

w3schools.com/python/python_strings_slicing.asp

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

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

ExampleGet your own Python Server

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

b = "Hello, World!"
print(b[2:5])

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:

Example

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

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

Slice To the End


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

Example

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

b = "Hello, World!"
print(b[2:])

Negative Indexing

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

Example
Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

2/2

You might also like