Open In App

String Slicing in Python

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

String slicing in Python is a way to get specific parts of a string by using start, end, and step values. It’s especially useful for text manipulation and data parsing.

Let’s take a quick example of string slicing:

s = "Hello, Python!"

# Slice string from index 0 to index 5 (exclusive)
s2 = s[0:5]

print(s2)

Output
Hello

Explanation: In this example, we used the slice s[0:5] to obtain the substring “Hello” from the original string.

Syntax of String Slicing in Python

substring = s[start : end : step]

Parameters:

  • s: The original string.
  • start (optional): Starting index (inclusive). Defaults to 0 if omitted.
  • end (optional): Stopping index (exclusive). Defaults to the end of the string if omitted.
  • step (optional): Interval between indices. A positive value slices from left to right, while a negative value slices from right to left. If omitted, it defaults to 1 (no skipping of characters).

Return Type

  • The result of a slicing operation is always a string (str type) that contains a subset of the characters from the original string.

String Slicing Examples

Let’s see how to use string slicing in Python with the examples below.

Retrieve All Characters

To retrieve the entire string, use slicing without specifying any parameters.

s = "Hello, World!"

# Get the entire string
s2 = s[:]
s3 = s[::]

print(s2)
print(s3)

Output
Hello, World!
Hello, World!

Explanation: Using [:] or [::] without specifying start, end, or step returns the complete string.

Get All Characters Before or After a Specific Position

To get all the items from a specific position to the end of the string, we can specify the start index and leave the end blank.
And to get all the items before a specific index, we can specify the end index while leaving start blank.

s = "Hello, World!"

# Characters from index 7 to the end
print(s[7:])

# Characters from the start up to index 5 (exclusive)
print(s[:5])

Output
World!
Hello

Explanation: The slice s[7:] starts from index 7 and continues to the end of the string.

Extract Characters Between Two Positions

To extract characters between specific positions, provide both start and end indices.

s = "Hello, World!"

# Characters from index 1 to index 5 (excluding 5)
print(s[1:5]) 

Output
ello

Get Characters at Specific Intervals

To retrieve characters at regular intervals, use the step parameter.

s = "abcdefghi"

# Every second character
print(s[::2])

# Every third character from index 1 to 8 (exclusive)
print(s[1:8:3]) 

Output
acegi
beh

Explanation: The slice s[::2] takes every second character from the string.

Out-of-Bounds Slicing

In Python, String slicing allows out-of-bound indexing without raising errors. If indices exceed the string length, the slice returns only available characters without raising an error.

Example: The slice s[3:15] starts at index 3 and attempts to reach index 15, but if string ends at index 8 then it will return only the available elements.

Using Negative Indexing in Slicing

Negative indexing is useful for accessing elements from the end of the String. The last element has an index of -1, the second last element -2, and so on.

Extract Characters Using Negative Indices

Below example shows how to use negative numbers to access elements from the string starting from the end. Negative indexing makes it easy to get items without needing to know the exact length of the string.

s = "abcdefghijklmno"

# Characters from index -4 to the end
print(s[-4:])

# Characters from the start up to index -3 (excluding -3)
print(s[:-3])

# Characters from index -5 to -2 (excluding -2)
print(s[-5:-2])

# Get every 2nd elements from index -8 to -1 (excluding index -1)
print(s[-8:-1:2])

Output
lmno
abcdefghijkl
klm
hjln

Reverse a String Using Slicing

To reverse a string, use a negative step value of -1, which moves from the end of the string to the beginning.

s = "Python"

# Reverse the string
print(s[::-1])

Output
nohtyP

Explanation: The slice s[::-1] starts from the end and steps backward through the string, which effectively reversing it. This method does not alter the original string.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg