Open In App

String Slicing in Python

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

How String slicing in Python works

For understanding slicing we will use different methods, here we will cover 2 methods of string slicing, one using the in-build slice() method and another using the [:] array slice. String slicing in Python is about obtaining a sub-string from the given string by slicing it respectively from start to end. 

Python slicing can be done in two ways:

  • Using a slice() method
  • Using the array slicing  [:: ] method

Index tracker for positive and negative index: String indexing and slicing in python. Here, the Negative comes into consideration when tracking the string in reverse. 

python-string-slice

Method 1: Using the slice() method

The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step).

Syntax:

  • slice(stop)
  • slice(start, stop, step)

Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the slicing of object stops. step: It is an optional argument that determines the increment between each index for slicing. Return Type: Returns a sliced object containing elements in the given range only. 

Example:

Python3




# Python program to demonstrate
# string slicing
 
# String slicing
String = 'ASTRING'
 
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
 
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])


Output:

String slicing
AST
SR
GITA

Method 2: Using the List/array slicing  [ :: ]  method

In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way to slice a string using list slicing and Array slicing both syntax-wise and execution-wise. A start, end, and step have the same mechanism as the slice() constructor. 

Below we will see string slicing in Python with examples.

Syntax

arr[start:stop]         # items start through 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 whole array
arr[start:stop:step]    # start through not past stop, by step

Example 1:

In this example, we will see slicing in python list the index start from 0 indexes and ending with a 2 index(stops at 3-1=2 ).

Python3




# Python program to demonstrate
# string slicing
 
# String slicing
String = 'GEEKSFORGEEKS'
 
# Using indexing sequence
print(String[:3])


Output:

GEE

Example 2:

In this example, we will see the example of starting from 1 index and ending with a 5 index(stops at 3-1=2 ), and the skipping step is 2. It is a good example of Python slicing string by character.

Python3




# Python program to demonstrate
# string slicing
 
# String slicing
String = 'GEEKSFORGEEKS'
 
# Using indexing sequence
print(String[1:5:2])


Output:

EK

Example 3:

In this example, we will see the example of starting from -1 indexes and ending with a -12 index(stops at 3-1=2 )and the skipping step is -2.

Python3




# Python program to demonstrate
# string slicing
 
# String slicing
String = 'GEEKSFORGEEKS'
 
# Using indexing sequence
print(String[-1:-12:-2])


Output:

SEGOSE

Example 4:

In this example, the whole string is printed in reverse order.

Python3




# Python program to demonstrate
# string slicing
 
# String slicing
String = 'GEEKSFORGEEKS'
 
# Prints string in reverse
print(String[::-1])


Output:

SKEEGROFSKEEG

Note: To know more about strings click here.

Using islice()
The islice() is a built-in function defined in itertools module. It is used to get an iterator which is an index-based slicing of any iterable. It works like a standard slice but returns an iterator.

Syntax:

itertools.islice(iterable, start, stop[, step])
Parameters: iterable: Any iterable sequence like list, string, tuple etc. start: The start index from where the slicing of iterable starts. stop: The end index from where the slicing of iterable ends. step: An optional argument. It specifies the gap between each index for slicing. Return Type: Return an iterator from the given iterable sequence.

Example:

Python3




# Python program to demonstrate
# islice()
  
import itertools
  
# Using islice()
String = 'GEEKSFORGEEKS'
  
# prints characters from 3 to 7 skipping one character.
print(''.join(itertools.islice(String, 3, 7)))
#This code is contributed by Edula Vinay Kumar Reddy


Output

KSFO


Previous Article
Next Article

Similar Reads

String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more. Syntax of list slicin
4 min read
Python | Reverse Slicing of given string
Sometimes, while working with strings we might have a problem in which we need to perform the reverse slicing of string, i.e slicing the string for certain characters from the rear end. Let's discuss certain ways in which this can be done. Method #1 : Using join() + reversed() The combination of above function can be used to perform this particular
5 min read
Python | Reverse Interval Slicing String
Sometimes, while working with strings, we can have a problem in which we need to perform string slicing. In this, we can have a variant in which we need to perform reverse slicing that too interval. This kind of application can come in day-day programming. Let us discuss certain ways in which this task can be performed. Method #1: Using String Slic
4 min read
Python | Reverse Incremental String Slicing
Sometimes, while working with Python strings, we can have a problem in which we need to perform the slice and print of strings in reverse order. This can have applications in day-day programming. Let us discuss certain ways in which this task can be performed. Method #1: Using loops This is the brute-force way in which this task can be performed. I
4 min read
Interesting facts about strings in Python | Set 2 (Slicing)
Creating a String Strings in Python can be created using single quotes or double quotes or even triple quotes. # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'
4 min read
Python Slicing | Reverse an array in groups of given size
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5, 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k =
5 min read
Python Slicing | Extract ‘k’ bits from a given position
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get o
4 min read
Python | Slicing list from Kth element to last element
Python list slicing slices the list from start index till end - 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let's discuss ways in which last element can be included during a list slice. Method #1 : Using None During list slicing, giving the d
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg