Python Slicing String

String slicing in python; Through this tutorial, i am going to show you what is string slicing and how to use string slicing.

Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end.

How to slice a string in python

The string slice in python is used to developed a new substring from the original string due to this there is effect is occurred in the original string it simply means the original string remains the same as it was it previous.

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 program for Slicing a string

# string slicing basic example
s = 'Hello World'
# extract zero to five index
x = s[:5]
print(x)
# extract 2 to 5 index character
y = s[2:5]
print(y)

After executing the program, the output will be:

Hello
llo

Example 2: Reverse a String using Slicing

# reverse a string in python
s = 'Hello World'
str = s[::-1]
print(str)

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]
print(s1)

After executing the program, the output will be:

or

Recommended Python Tutorials

Leave a Comment