String Slicing in Python

String Slicing in Python

String slicing in python; In this tutorial, we would like to share with how to slice string by character, reverse string using slicing and negative index slice in python.

When slicing strings, we are creating a substring, which is essentially a string that exists within another string. By including only the index number before the colon and leaving the second index number out of the syntax, the substring will go from the character of the index number called to the end of the string.

How to slice a string in python

First of all, you should know the slice method of python, which is used to slice a given string.

In python, slice() function can use used to slice strings, lists, tuple etc and returns a slice object.

The syntax of slice() is:

slice(start, stop, step)

slice() Method Parameters

slice() can take 3 parameters:

  • start (optional) – Starting integer where the slicing of the object starts. Default to None if not provided.
  • stop – Integer until which the slicing takes place. The slicing stops at index stop -1 (last element).
  • step (optional) – Integer value which determines the increment between each index for slicing. Defaults to None if not provided.

Example 1: python slice string by character

# string slicing basic example

s = 'Hello World'
# extract zero to five index
x = s[:5]

# extract 2 to 5 index character
y = s[2:5]

After executing the program, the output will be:


Example 2: Python reverse string using slicing

# reverse a string in python

s = 'Hello World'

str = s[::-1]


After executing the program, the output will be:

dlroW olleH

Example 3: Python negative index slice

# nagetive index string slicing

s = 'Hello World'

s1 = s[-4:-2]


After executing the program, the output will be:


Recommended Python Tutorials


My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *