The IoT Academy Blog

What is Slicing Strings in Python- Explained with Examples

  • Written By  

  • Published on August 25th, 2023

Introduction

Slicing in Python refers to extracting specific portions (substring) of a string using indices. Slicing strings Python involves obtaining a sub-string from a given string by slicing it from start to end. Using index positions, slicing allows you to capture substrings or characters, creating more flexible manipulation and analysis of text data. Moreover, one can return an array of characters with the slice syntax.

This blog will thoroughly explain string slicing in python, syntax, examples, and how indexing can be done in Python.

How does Python Slice Strings Operate?

A slice syntax helps you to return a range of characters. You have to define the start and the end index. Separate them by a colon, to return a part of the string.

Example:

Get the characters from 2nd position to 6th position (which is not included):

b = "Welcome, Home"

print(b[2:6])

Output : lcom

Methods for Slicing Strings in Python

For slicing, you can use different methods among which two are very common. One is by using the in-build slice() another is by using the [:] array slice. 

Using a slice() method

In this method, the slice() constructor creates a slice object. Thus, this object represents the set of indices. A range like start, stop, and step is there to specify it. Below is the syntax to explain string slicing in Python via this method.

Syntax:

slice(stop)

slice(start, stop, step)

Parameters:
 

  • start: Starting index where object slicing begins. 
  • stop: the index at which the object's slicing comes to an end. 
  • step: It is a free-form input that specifies the slicing increment between each index. 

Return Type: Delivers a sliced object with only the elements in the given range. 

Using the array slicing [:: ] method

In slicing strings Python learning, you can also use indexing syntax as an alternative for the slice object. Moreover, this is an easy way of slicing a string via list slicing and Array slicing. It is convenient both syntax-wise and execution-wise. The process of a start, end, and step is the same as that of the slice() constructor. 

Syntax:
 

  • arr[start:stop] : Items begin with stop-1.
  • arr[start:] : items start through the rest of the array
  • arr[:stop] : items from the beginning through stop-1
  • arr[:] : a copy of the entire array
  • arr[start:stop:step] : beginning with not past stop, by step

String Slicing in Python with Example

Let's understand basic string slicing operations with examples.
 

  • Example 1
     

S = 'DICTIONARY'

print(S[2:7]) # CTION
 

  • Example 2 

Slicing with Negative Indices

When slicing a string, you can also specify negative indices.

S = 'DICTIONARY'

print(S[-7:-2]) # ANOIT
 

  • Example 3

Slicing strings in Python with Positive & Negative Indices

It is possible to define both positive and negative indices simultaneously.

S = 'ABCDELGHK'

print(S[2:-5]) # CD
 

  • Example 4

Specify Step for the slice- Using the step parameter, you can define the slicing step. The optional step parameter has a default value of 1.

# Return every second item between positions 2 to 7

S = 'AMCDEKGHK'

print(S[2:7:2]) # CEG
 

  • Example 5

Reversing a String- You can reverse a string by leaving off the start and stop indices and entering a step of -1.

S = 'MONDAY'

print(S[::-1]) # YADNOM

Indexing In Python

So far we have seen slicing strings in Python. But, Indexing is different from it. Indexing is referring to an item of an iterable by its place within the iterable. Each character in a string has an index number that you can use to retrieve that character in the string. 

Accessing characters in a String can be done in these two ways:
 

  • Accessing Characters by Positive Index Number
  • Accessing Characters by Negative Index Number

Indexing starts from 0 in Python. Thus, the first element in a sequence is at position 0. The second element appears at position 1, and so forth.

To reach an element in a sequence, use square brackets [] with the index of the element you need to access.

Consider the below example:

my_list = ['monday', 'tuesday', 'wednesday', 'date']

print(my_list[0]) # output: 'Monday'

print(my_list[1]) # output: 'tuesday'

String Indexing and Slicing in Python

Omitting the starting index will slice all characters from the string's start to a specific point in the middle. Now, provide the end index. The range starts at the first character and goes all the way to the last character before the end index.

The syntax for this notation:

string[:end_position]. 

Slicing a string's first five characters:

string[:5]

This results in a substring that runs from index 0 to index 4.

testString2 = "Welcome! Home"

print(testString2[:5])

Welco

By passing the starting index, all characters from the beginning of the string to a specific point in the centre will be cut. Now, provide the end index as usual. The range begins at character zero. But, it extends all the way to character zero before the end index.

The syntax for python slice string by character:

string[start_position:]

testString2 = "Welcome! Home"

print(testString2[5:])

e! Home

Slicing Strings with Negative Indexing

Slicing strings is also possible with negative indexing. This also helps extract the second and third final characters from a string. But there is no need to carry out a lot of logical procedures. The same principles of positive and negative indexing apply to cutting. It denotes the beginning of the substring and is inclusive. But, the first character that is excluded from the new substring by the ending position, which is exclusive, is marked.

testString2 = "Welcome! Heaven"

print(testString2[-3:-1])

ve

Conclusion

Python supports slicing strings to create substrings. Because Python strings are immutable, cutting a string into smaller pieces results in the original string remaining the same. You can better understand slicing strings in Python by practising the various syntax we have discussed. For more knowledge on Python index and strings, join the Python certification course by The IoT Academy!

Frequently Asked Questions

Q.What is the 2 :] in Python?

Ans. [2: ] is a slice notation. You can perform it on a str. Hence, you can retrieve all of the characters of the string beginning from index 2.

Q.What is the difference between split () and slicing in Python?

Ans.A separator defines how to split a string. It can be by a comma, character etc. Whereas, a Limit Limits the number of splits for a given number.

Q.What is the difference between the slice () and substring () methods?

Ans.The main difference between the two is that of the parameters. The two parameters of substr() are start and length. But for substring(), they start and end.

About The Author:

logo

Digital Marketing Course

₹ 9,999/-Included 18% GST

Buy Course
  • Overview of Digital Marketing
  • SEO Basic Concepts
  • SMM and PPC Basics
  • Content and Email Marketing
  • Website Design
  • Free Certification

₹ 29,999/-Included 18% GST

Buy Course
  • Fundamentals of Digital Marketing
  • Core SEO, SMM, and SMO
  • Google Ads and Meta Ads
  • ORM & Content Marketing
  • 3 Month Internship
  • Free Certification
Trusted By
client icon trust pilot
1whatsapp