How to Slice a String in Python?

Python – Slice a String

To slice a String in Python, use slice() builtin function.

slice() builtin function returns a slice object. And we can use this slice object to slice a string. All we need to do is, pass the slice object as an index in the square brackets after the string variable. This expression returns the sliced string.

The following is a sample code snippet to slice a string with specific value for stop parameter in slice function.

string_object = ''
slice_object = slice(stop)
string_slice = string_object[slice_object]

The following is a sample code snippet to slice a string with specific value for start, stop and an optional step parameter in slice function.

string_object = ''
slice_object = slice(start, stop[, step])
string_slice = string_object[slice_object]

Example 1: Slice String with Specific End Position

In this example, we will prepare a slice object with specific end/stop position stop=5, and use this slice object to slice the string.

Python Program

string1 = 'hello-world'
stop = 5 #end position
slice_object = slice(stop)
result = string1[slice_object]
print(result)
Run

Output

hello

The slice object would contain the indices [0, 1, 2, 3, 4] for given stop value. And the characters in the string corresponding to these indices are [h, e, l, l, o]. Hence the resulting string of 'hello'.

Example 2: Slice String with Specific Start and End Positions

In this example, we will prepare a slice object with specific start and stop positions, and use this slice object to slice the string.

Python Program

string1 = 'hello-world'
start = 2 #start position of slice in string
stop = 5 #end position of slice in string
slice_object = slice(start, stop)
result = string1[slice_object]
print(result)
Run

Output

llo

The slice object would contain the indices [2, 3, 4] for given start and stop values. And the characters in the string corresponding to these indices are [l, l, o], Hence the resulting string of 'llo'.

Example 3: Slice String with Specific Start and End Positions, Step

In this example, we will prepare a slice object with specific start and stop positions, and also a specific value for step. We shall then use this slice object to slice the string.

Python Program

string1 = 'hello-world'
start = 2 #start position of slice in string
stop = 9 #end position of slice in string
step = 2
slice_object = slice(start, stop, step)
result = string1[slice_object]
print(result)
Run

Output

lowr

The slice object would contain the indices [2, 4, 6, 8]. And the characters in the string corresponding to these indices are [l, o, w, r], Hence the resulting string of 'lowr'.

Summary

In this tutorial of Python Examples, we learned how to slice a string, using slice() builtin function.