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]

Examples

1. Slice the given string with specific end position

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

Python Program

myStr = 'hello-world'
stop = 5 #end position of slice in string

slice_object = slice(stop)
result = myStr[slice_object]

print(result)
Run Code Copy

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'.

2. Slice the given string with specific start and end positions

In this example, we take a string in myStr, and prepare a slice object with start=2 and stop=5, and use this slice object to slice the string in myStr.

Python Program

myStr = 'hello-world'
start = 2 #start position of slice in string
stop = 5 #end position of slice in string

slice_object = slice(start, stop)
result = myStr[slice_object]

print(result)
Run Code Copy

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'.

3. Slice the given string with specific start and end positions, and step value

In this example, we take a string in myStr, and prepare a slice object with start index = 2, and stop index = 9, and also with a step value of 2. We shall then use this slice object to slice the string in myStr.

Python Program

myStr = '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 = myStr[slice_object]

print(result)
Run Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍