Slicing in Python

Slicing in Python

9 mins read2.3K Views Comment
Updated on Nov 25, 2022 19:24 IST

Strings are ordered collections of characters, which is why you can access the items (or characters) of the string based on their position. This we refer to as indexing. Using indexing operations you can get back the one-character string at the position or offset that you specify. Now, what if you want to get a section of the string rather than a single character? We call that slicing.


Table of Contents

What is String Slicing?

Slicing is basically a generalized form of indexing that returns an entire section in a single step, instead of a single item. For example, you can extract columns of data, strip off leading and trailing characters, and much more. The concept of slicing is very simple. When you index a string using a pair of offsets separated by a colon (:), Python returns a new string object containing the section identified by the offset pair. So, the left offset, lower bound is inclusive and the right offset, upper bound is non-inclusive. If you don’t specify the offset, the left and right bounds default to value 0 and the length of the string that you are slicing, respectively.


Let’s consider a few simple examples.

#Example 1
string1 = "Python is my favorite programming language!"
print(string1[:6]) #specifying only the stop position (right offset)
print(string1[10:]) #specifying only the start position (left offset)
print(string1[13:22]) #specifying left & right offset
print(string1[:-3]) #fetches all but last three characters of string1
Copy code

In the above example, string1[:6] extracts items from offset 0 to offset 5. Similarly, string[10:] fetches items from the 10th position till the end. String[:-3] fetches all but the last item, since the lower bound is 0, and -1 refers to the last item, not inclusive. To summarize,

  • str[start:end]: Fetches all characters from start to end – 1
  • str[:end]: Fetches all characters from the beginning of the string to end – 1
  • str[start:]: Fetches all characters from start to end of the string

What better way to learn a concept than to implement it! So, let us check out some examples.

How to Generate a Sub-string in Python?

We can use a technique called slicing to extract substring in Python. Now that you are aware of what slicing is let us try to use it to perform some common slicing operations.

Get the first n characters of string in Python

Let us retrieve the first 6 characters from a string. You can just give the upper bound or right offset, which is non-inclusive.

#Example 2: Get first 6 characters of string
string1 = "Python Code"
Copy code

Get the last n characters of string in Python

Let us retrieve the last 6 characters from a string. To do so you need to give the negative left offset.

#Example 3: Get last 4 characters of string
string1 = "Python Code"
Copy code

Slicing in Python with negative indices

As you already know you can use negative index values to perform slicing operations. Let us try to use negative indices at the start position and at the stop position.

#Example 4: Using negative indices
string1 = "Python/Code"
Copy code

From the above example, we can incur the following points:

  • string[-start: ] – With negative indicates, the parsing will begin from the last position and the left offset is always inclusive. So, the line string1[-4:] from the above example gets the last 4 characters (or items) of the string.
  • string[:-stop ] – The right offset is always non-inclusive and by using negative right offset (or upper bound), we are trying to exclude the n characters from the last. In the above example, string1[:-4] excludes the last 4 characters of the string and returns rest of the characters of the string
  • string[-start:-stop] – In the code string1[-4:-1], the left offset is the 4th character from the end(inclusive) and the right offset is the last character (non inclusive). Using offset pairs [-4, -1], we are fetching items from the 4th character from the end to the last but 1 character.

Slicing with positive and negative indices

Now let’s try using a combination of negative and positive indices.

#Example 5: Using negative & positive indices
string1 = "Python/Code"
Copy code

In the above example, the offset pair [1:-4], fetches from offset 1 (i.e. from the character ‘y’) till the last but 5th item. Remember that the right offset is non-inclusive. The second line of the code probably doesn’t make sense. You are asking Python to start slicing from the last but 4th position till the 1st position from the beginning.

Slicing with steps

Python 2.3 and later versions support an optional 3rd parameter in the slicing operation, which we call step (or sometimes called a stride). The step is added to the index of each item that you extract. The syntax now looks something like string[I, J, K], which means “extract substring in X from offset I through J-1, by K. The default value of K is 1. You can use this optional parameter to skip items or reverse their order.

Let’s take a look at an example:

#Example 6: Slicing with steps
str1 = 'abcdefghijklmnopqrst'
Copy code

In the above example, str1[1:17:2] will fetch every item from offset 1 till 16, by adding step 2 to the index of every item it fetches, that is, it will fetch the items at offsets 1, 3, 5, 7, 9, 11, 13, and 15. Similarly, str1[ : : 3] will fetch every item from offset 0 till the end of the string, with stride 3, that is, it will fetch items at offsets 0, 3, 6, 9, 12, 15, 18.

Slicing from beginning till end

Using slicing operations you can extract from the beginning of the string to the end in a simple way. In other words, you are simply making a full top-level copy of a sequence object, in our case a string. This object will have the same value as the original one, but a different memory location.

#Example 7: Slicing from beginning till end
str1 = 'abcdefghijklmnopqrst'
Copy code

Let us further explore slicing and other string methods with help of some interesting examples.

How To Check if a Substring is Present Within a String in Python?

You can check if a substring is present within a string in multiple ways in Python. Let us look at a few of them.

#Example 8: To find if substring is within a string
#Using in operator
string = 'abcdefghijklmnopqrst'
substring = 'ghi'
print(substring in string)
#using str.index() method
string = 'abcdefghijklmnopqrst'
try :
result = str.lower().index("lmop")
print ("lmop is present in the string.")
except :
print ("lmop is not present in the string.")
#using find() method
string = 'abcdefghijklmnopqrst'
if string.lower().find("pqrs") != -1:
print("Sibstring found at index:", string.find("pqrs"))
print("Does not exist")
Copy code

In the example above, I have shown three ways that you can use to check if a substring is present in the string.

  1. In the first method, I have used in operator. The in operator True if the substring is present and False if its not
  2. Secondly, I have used the str.index() method.
    1. The index() method returns the starting index of the substring if a substring is present
    2. If the substring is not present it returns ValueError. We can solve this using Try Except as shown in the example
    3. index() is case sensitive, make sure you use .lower() function to avoid bugs
  3. The last method that I used is str.find()
    1. Just like index(), the find() method also returns the starting index of the substring if present
    2. If the substring is not present it returns -1, which is negative index of the leftmost character
    3. find() is case sensitive, make sure you use .lower() function to avoid bugs

How To Get the Character of a Given Index in a String in Python?

You have already learned how to slice a string and the concept of indexing. You can use these concepts to get a character at a given index or offset in a string.

#Example 9: Access character based on index
sampleStr = "Hello! I am using Python"
# Check the size of string before accessing character by index
n = 12
if n < len(sampleStr) :
print( sampleStr[n])
print( sampleStr[n:n+5])
else :
print ("Index : Out of range")
Copy code

Also, it’s always better to check if the given index is less than the length of the string before using the slicing operations,

How to Create a List of Substrings From a String in Python?

Often you might come across problems where you need to fetch all the possible substrings of a string. While there are various ways to achieve it, let’s do it using list comprehension and string slicing operations.

So, have you heard of list comprehensions? List comprehensions offer a very elegant way to define and create lists based on other iterables like tuples, strings, arrays, lists, etc. They are more time-efficient than loops and require fewer lines of code.

#Example 10: List of substrings from a string
string1 = "Python"
res_strings = [string1[i: j] for i in range(len(string1))
for j in range(i + 1, len(string1) + 1)]
Copy code

Notice that in the loop for ‘j’ , the range is from i + 1 to len(string1)+1, because the right offset is non-inclusive.

How to Reverse a String in Python with Negative Offsets?

Earlier we already learned about slicing with steps. However, we only used a positive step (or stride). You can also use a negative stride. By using negative steps, the first two bounds are essentially reversed. Reversing is one of the most common use cases from three-limit slices.

Here’s how to reverse a string using slicing with stride.

#Example 11: Reverse a string using three-limit slices
string1 = "Python"
string2 = 'abcedfg'
Copy code

The points that we can infer from the above example are:

  • In string1[::1], both upper bound and lower bound are default, that is, 0 and length of the string respectively. Stride of -1 indicates that the slicing operation should take place from right to left instead of the usual way, which is left to right. The result is that the string gets reversed
  • In string1[5, 1, -1], the upper bound and the lower bound are essentially reversed. And a negative stride indicates we start slicing from right. The slice string1[5, 1, -1] fetches the items from 2 to 5, in reverse order

How to Count the Frequency of Substring in a String?

You can find the occurrences of a substring in a given in a couple of ways. Let us explore them in detail.

Using count() method

string.count() is a built-in function that returns the count of occurrences of a substring in a given string. The syntax is string.count(substring, [start_index], [end_index]), where:

  • substring – is the string whose count has to be found
  • start_index (optional) – is the starting index within the string where the search starts
  • end_index (optional) – is the ending index within the string where the search ends

Remember that the index in Python starts from 0, not 1.

#Example 12: Count number of occurrences
string1 = "Python is the best, isn't it?"
substring = "is"
count = string1.count(substring)
print("The count is:", count)
count = string1.count(substring, 5, 12) #using start_index & end_index
print("The count is:", count)
Copy code

Using len() and string slicing

In this technique, first, we are splitting the main string using the substring as a separator parameter of str.split() function. Then we are counting the number of occurrences using the len() method, which is one more than the required value. Therefore, we are then subtracting 1 from the result of the len operation.

#Example 13: Count occurences using len + string slicing
string1 = "Python is the best, isn't it?"
substring = "is"
count = len(string1.split(substring))-1
print("The frequency of substring in the given string is " + str(count))
Copy code

With this, we have completed string slicing in Python. Though at first glance they may seem confusing, the concepts of indexing and slicing are very simple and powerful once you get the gist.

Let us now go a step further and explore how to modify strings using string methods that we have learned about in previous articles.

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio