Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Slicing a String?
3.
How String Slicing in Python works?
4.
Why is Python String Slicing Useful? 
5.
Methods of String Slicing in Python
6.
Slice() Method
6.1.
Syntax:
7.
Slice() Method Examples
7.1.
Example - 1
8.
Python
8.1.
Example - 2
9.
Python
9.1.
Example - 3
10.
Python
10.1.
Example - 4
11.
Python
12.
List Slicing / Array Slicing
12.1.
Syntax:
12.2.
List Slicing / Array Slicing Examples
12.2.1.
Example - 1
12.3.
Python
12.3.1.
Example - 2
12.4.
Python
12.4.1.
Example - 3
12.5.
Python
12.5.1.
Example - 4
12.6.
Python
13.
Slice Operation on Lists and Tuple
13.1.
Example:# Otput: (11, 13)
13.2.
Python
14.
Frequently Asked Questions
14.1.
What is Python list slicing?
14.2.
When slicing in Python, What does the 2 in [::2] specify?
14.3.
How can you skip letters in slicing strings?
15.
Conclusion
Last Updated: Apr 1, 2024
Easy

What is String Slicing in Python?

Author Nagendra
0 upvote

Introduction

Hey Ninjas!! Welcome to another article on Python. Strings are immutable data types in Python. We cannot update the string's value. Slicing strings create a substring from the original string. Do you know we can easily slice the letters of the string? Today we will learn about String Slicing in Python. We will also look into details of the methods of String Slicing in Python.

String slicing in Python

The article explains the details of string slicing in Python. Let's get started.

What is Slicing a String?

Slicing means extracting a part from something, and slicing a string means extracting some part from a string. This extracted part is also referred to as a sub-string. In short, string slicing in Python is obtaining a substring from a larger string by slicing it based on specific criteria. String slicing allows us to obtain a specific range of characters from a string based on their respective indices.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How String Slicing in Python works?

String slicing in Python allows you to extract a portion of a string by specifying a start and end index. It follows the format string[start:end], where start is the index where slicing begins (inclusive) and end is the index where it ends (exclusive).

For example, with the string my_string = "Hello, World!", if you use my_string[7:12], it will return "World".

If you omit start, it starts from the beginning of the string. If you omit end, it goes to the end of the string.

Negative indices are also valid. string[-1] refers to the last character, string[-2] refers to the second last, and so on.

Why is Python String Slicing Useful? 

Python string slicing is advantageous for a number of factors:

  • Subsetting Data: It makes it simple to access and manipulate substrings inside a bigger text since it enables you to extract specific chunks of a string
  • Data Extraction: It makes the process of sifting through strings to find relevant information and extracting it, which is essential for tasks like data cleaning and analysis, simpler
  • String Manipulation: Slicing makes it easier to manipulate strings in a variety of ways, including reversing strings and extracting words or characters for additional use
  • Efficient Access: Slicing offers direct access to a segment rather than iterating through a string character by character, which may be more effective for some jobs
  • Substring Creation: It permits the creation of substrings for activities like producing distinctive IDs, decoding file paths, or producing outputs with specific formatting
     

Methods of String Slicing in Python

String slicing in Python can be performed using two methods:

  1. Slice() Method
  2. List Slicing / Array Slicing
     

Let's look into the details of each of them.

Slice() Method

The slice() method returns an object containing the range of string slicing. The parameter includes a set of range of values defined as (start, stop, step). Let's look at the syntax of the slice method().

Syntax:

slice( Start_Index, End_Index, Steps )

 

Here, Start_Index is the starting index of the string. End_Index is the last index before which all elements are considered. Steps are the number of steps to be jumped in each iteration. The Start_Index and Steps are optional. The Start_Index is 0 by default. The step is 1 by default.

Slice() Method Examples

Example - 1

When only one parameter is passed to the slice() method, it takes it as the end index.

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[slice(6)])


Output:

Coding


Explanation:

The slice(6) method slices the string from starting to index 6 (excluding) and prints the result.

Example - 2

You can slice strings within a given range. Have a look at the following example:

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[slice(2,10)])


Output:

ding Nin


Explanation:

The slice(2,10) method slices the string from index 2 to index 9 and prints the result.

Example - 3

String Slicing in Python can be performed within a given range by skipping the values.

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[slice(2,10,3)])


Output:

dgi


Explanation:

The slice(2,10,3) method slices the string from index 2 to index 9 and prints every 3rd letter.

Example - 4

The String Slicing in Python can also be performed on backward indexing.

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[slice(-10,-3)])


Output:

ing Nin


Explanation:

The above code snippet uses backward indexing. The slice(-10,-3) method slices the string from index -10 to index -4 and prints them.

List Slicing / Array Slicing

The List Slicing method is the most common way of string slicing in Python. The parameter includes a set of range of values defined as [start, stop, step]. Let's look at the syntax:

Syntax:

string[ Start_Index : End_Index : Steps ] 

 

Here, Start_Index is the starting index of the string. End_Index is the last index before which all elements are considered. The step is the number of steps to be jumped in each iteration. Let's look at a few examples to understand string slicing in python.

List Slicing / Array Slicing Examples

Example - 1

Slicing a string within a given range

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[7:12])


Output:

Ninja


Explanation:

The above code snippet prints the letters from index 7 to index 11.

Example - 2

You can slice the string within a given range by skipping the letters. 

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[1:12:2])


Output:

oigNna


Explanation:

The above code snippet prints every 2nd letter from index 1 to index 11.

Example - 3

When the starting index is not given, it takes 0 as the starting index.

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[:7])


Output:

Coding 


Explanation:

The above code snippet prints the letters from index 0 to index 6.

Example - 4

When the end index is not provided, it takes the last index as the end index.

Code:

  • Python

Python

string = 'Coding Ninjas'
print(string[4:])


Output:

ng Ninjas


Explanation:

The above code snippet prints the letters from index 4 to the last index.

Slice Operation on Lists and Tuple

Slice operation allows you to access a subset of elements from a list or tuple in Python. It's a powerful feature that provides a concise way to extract specific portions of a sequence.

Example:# Otput: (11, 13)

  • Python

Python

# Slicing lists
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Extracting elements from index 2 to 5 (exclusive)
subset_list = my_list[2:5]
print(subset_list)

# Extracting every second element from index 1 to 7 (exclusive)
subset_list_2 = my_list[1:7:2]
print(subset_list_2)

# Extracting elements from index 3 to the end of the list
subset_list_3 = my_list[3:]
print(subset_list_3)

# Slicing tuples
my_tuple = (11, 12, 13, 14, 15)

# Extracting elements from index 1 to 3 (exclusive)
subset_tuple = my_tuple[1:3]
print(subset_tuple)

# Extracting every second element from index 0 to 4 (exclusive)
subset_tuple_2 = my_tuple[0:4:2]
print(subset_tuple_2)

Output

[3, 4, 5]
[2, 4, 6]
[4, 5, 6, 7, 8, 9, 10]
(12, 13)
(11, 13)

 

In the examples above, slices are specified using the syntax [start:stop:step], where start is the starting index (inclusive), stop is the ending index (exclusive), and step is the step size (optional, default is 1). This operation works for both lists and tuples.

Frequently Asked Questions

What is Python list slicing?

In Python, list slicing is a common string slicing method. It is a technique to extract some specific data portion from a string. It is a flexible method to manipulate the data based on specific requirements.

When slicing in Python, What does the 2 in [::2] specify?

The 2 in [::2] specifies the step size, indicating that every second element should be included in the sliced sequence. It skips one element after including each element during slicing.

How can you skip letters in slicing strings?

In Python, you can skip letters in string slicing by specifying the step parameter in slice notations. You need to pass the step parameter along with starting index and end index to skip letters in slicing strings.

Conclusion

In this article, we have extensively discussed the details of String Slicing in Python and Methods of String Slicing in Python. We hope that the blog has helped you enhance your knowledge regarding this topic.

Recommended Readings:

Happy Coding!!

Previous article
Strings in Python
Next article
Python String replace() Method
Live masterclass