free stats

Python Strings Slicing

Last Update : 12 Feb, 2023 Python, Programming

In this tutorial, you will learn about slicing a string in Python. 

Slicing strings in Python is a method of extracting a portion of a String and creating a new String from the extracted portion. 

This is done using square brackets " [ ] " and a colon " : " to specify the start and end indices of the slice and an optional step value. 

The basic syntax for slicing a string in Python is as follows.

string[start:end:step]

The explanation of the above string slicing syntax is as follows.

start - The starting index of the slice (inclusive). If omitted, it defaults to 0.

end - The ending index of the slice (exclusive). If omitted, it defaults to the length of the string.

step - The step value that specifies the number of characters to skip between each extracted character. If omitted, it defaults to 1.

 

You can learn Python string slicing by studying the following example. 

string = "Hello, UXPython"

# extract all characters from index 1 to index 5 (exclusive)
sliced_string = string[1:5]
print(sliced_string)

# extract all characters from index 0 to index 7 (exclusive), with a step of 2
sliced_string = string[0:7:2]
print(sliced_string)

# extract all characters from index 7 to the end of the string
sliced_string = string[7:]
print(sliced_string)

# extract all characters from the beginning of the string to index 5 (exclusive)
sliced_string = string[:5]
print(sliced_string)

# extract all characters from the string with a step of 2
sliced_string = string[::2]
print(sliced_string)

This program produces the following result -:

ello
Hlo 
UXPython
Hello
Hlo Xyhn

 

When you slice a string, it creates a new string, Also, the original string value remains unchanged.

 

You found this tutorial / article valuable? Need to show your appreciation? Here are some options:

01. Spread the word! Use following buttons to share this tutorial / article link on your favorite social media sites.

02. Follow us on Twitter, GitHub ,and Facebook.