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]
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: Python reverse 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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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