string slicing in python examples

String Slicing in Python with Examples

In our previous tutorial we have seen how to access each characters from a string individually through indexes. In this tutorial you will learn about String slicing in Python. String slicing is used to grab sub section of a given string i.e., to extract substrings from a string.

String Slicing in Python

string slicing in python examples

String slicing in Python can be done in two ways. They are as follows:

  • slice() constructor
  • Extending string indexing

slice() constructor – string slicing example

The Python slice() function is a constructor that is used to create a Python Slice object representing set of indices specified by the range(start, stop, step).

Following is the syntax for Python slice() function.

slice(start, stop, step)


start– starting index to specify where the slicing of object should begin.
stop– ending index to specify where the slicing of object should stop.
step– this is an optional argument to specify how much increment to be done between each index for slicing.

For example,

Below is the program to demonstrate string slicing using Python slice() constructor function with both positive and negative numbers for indices.

mystring ='abcdefxyz'
str1 = slice(2)
str2 = slice(1, 6, 2) 
str3 = slice(-1, -10, -2)
print("String slicing demo") 


String slicing demo

Extending string indexing

In this section let’s see how to expand the syntax of string indexing to extract substrings from a given string in Python.



Note, start, end and step work very similar to slice() constructor arguments.

Here are some string slicing examples.

>>> mystring = "Hello World"

>>> mystring[1:5]

>>> mystring[0:3]

>>> mystring[1:10]
'ello Worl'

Note, you can also omit the first or last index as shown below:

>>> mystring = "Hello World"

>>> mystring[1:]
'ello World'

>>> mystring[:10]
'Hello Worl'

>>> mystring[:]
'Hello World'

Also, you can use len() function to specify index value as shown below.

>>> mystring[1:len(mystring)]
'ello World'

Here is an example for negative index slicing.

>>> mystring[-10:-1]
'ello Worl'

>>> str[1:10]
'ello Worl'

Index slicing with stride

What is stride ?

String slicing can also accept a third argument step, called as stride , this refers to how many characters you want to move forward after the first character is fetched from the string. The default value of stride is set to 1.

Here are some examples how to slice with a stride i.e., with third argument.

>>> mystring = "Hello World"

>>> mystring[0:7:1]
'Hello W'

>>> mystring[1:10:2]
'el ol'

>>> mystring[::2]

>>> mystring[2::2]

That’s it. Therefore, you had learnt string slicing in Python using slice() constructor function and extending index slicing method. And also learnt what is stride and how to use them to extract substring from a given string.

Hope it helped 🙂

You’ll also like:


Inline Feedbacks
View all comments