The Wayback Machine - https://web.archive.org/web/20241110143214/https://www.geeksforgeeks.org/string-slicing-in-python/
Open In App

String Slicing in Python

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

String slicing in Python is a way to get specific parts of a string by using start, end, and step values. It’s especially useful for text manipulation and data parsing.

Let’s take a quick example of string slicing:

Python
s = "Hello, Python!"

# Slice string from index 0 to index 5 (exclusive)
s2 = s[0:5]

print(s2)

Output
Hello

Explanation: In this example, we used the slice s[0:5] to obtain the substring “Hello” from the original string.

Syntax of String Slicing in Python

substring = s[start : end : step]

Parameters:

  • s: The original string.
  • start (optional): Starting index (inclusive). Defaults to 0 if omitted.
  • end (optional): Stopping index (exclusive). Defaults to the end of the string if omitted.
  • step (optional): Interval between indices. A positive value slices from left to right, while a negative value slices from right to left. If omitted, it defaults to 1 (no skipping of characters).

Return Type

  • The result of a slicing operation is always a string (str type) that contains a subset of the characters from the original string.

String Slicing Examples

Let’s see how to use string slicing in Python with the examples below.

Retrieve All Characters

To retrieve the entire string, use slicing without specifying any parameters.

Python
s = "Hello, World!"

# Get the entire string
s2 = s[:]
s3 = s[::]

print(s2)
print(s3)

Output
Hello, World!
Hello, World!

Explanation: Using [:] or [::] without specifying start, end, or step returns the complete string.

Get All Characters Before or After a Specific Position

To get all the items from a specific position to the end of the string, we can specify the start index and leave the end blank.
And to get all the items before a specific index, we can specify the end index while leaving start blank.

Python
s = "Hello, World!"

# Characters from index 7 to the end
print(s[7:])

# Characters from the start up to index 5 (exclusive)
print(s[:5])

Output
World!
Hello

Explanation: The slice s[7:] starts from index 7 and continues to the end of the string.

Extract Characters Between Two Positions

To extract characters between specific positions, provide both start and end indices.

Python
s = "Hello, World!"

# Characters from index 1 to index 5 (excluding 5)
print(s[1:5]) 

Output
ello

Get Characters at Specific Intervals

To retrieve characters at regular intervals, use the step parameter.

Python
s = "abcdefghi"

# Every second character
print(s[::2])

# Every third character from index 1 to 8 (exclusive)
print(s[1:8:3]) 

Output
acegi
beh

Explanation: The slice s[::2] takes every second character from the string.

Out-of-Bounds Slicing

In Python, String slicing allows out-of-bound indexing without raising errors. If indices exceed the string length, the slice returns only available characters without raising an error.

Example: The slice s[3:15] starts at index 3 and attempts to reach index 15, but if string ends at index 8 then it will return only the available elements.

Using Negative Indexing in Slicing

Negative indexing is useful for accessing elements from the end of the String. The last element has an index of -1, the second last element -2, and so on.

Extract Characters Using Negative Indices

Below example shows how to use negative numbers to access elements from the string starting from the end. Negative indexing makes it easy to get items without needing to know the exact length of the string.

Python
s = "abcdefghijklmno"

# Characters from index -4 to the end
print(s[-4:])

# Characters from the start up to index -3 (excluding -3)
print(s[:-3])

# Characters from index -5 to -2 (excluding -2)
print(s[-5:-2])

# Get every 2nd elements from index -8 to -1 (excluding index -1)
print(s[-8:-1:2])

Output
lmno
abcdefghijkl
klm
hjln

Reverse a String Using Slicing

To reverse a string, use a negative step value of -1, which moves from the end of the string to the beginning.

Python
s = "Python"

# Reverse the string
print(s[::-1])

Output
nohtyP

Explanation: The slice s[::-1] starts from the end and steps backward through the string, which effectively reversing it. This method does not alter the original string.



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
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 | Custom slicing in List
Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination of above functions can be used to perform this pa
2 min read
Program to cyclically rotate an array by one in Python | List Slicing
Given an array, cyclically rotate the array clockwise by one. In this article, we will see how to cyclically rotate an array by one in Python. Example Input: arr = [1, 2, 3, 4, 5]Output: arr = [5, 1, 2, 3, 4]Reference: Program to cyclically rotate an array by one Python Program to Cyclically Rotate an Array by One in PythonBelow are the methods or
2 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
Slicing with Negative Numbers in Python
Slicing is an essential concept in Python, it allows programmers to access parts of sequences such as strings, lists, and tuples. In this article, we will learn how to perform slicing with negative indexing in Python. Indexing in PythonIn the world of programming, indexing starts at 0, and Python also follows 0-indexing what makes Python different
6 min read
Python slicing multi-dimensional arrays
Python's NumPy package makes slicing multi-dimensional arrays a valuable tool for data manipulation and analysis. It enables efficient subset data extraction and manipulation from arrays, making it a useful skill for any programmer, engineer, or data scientist. Python Slicing Multi-Dimensional ArraysSlicing is a method for taking out an array secti
4 min read
Python List Slicing
Python list slicing is fundamental concept that let us easily access specific elements in a list. In this article, we’ll learn the syntax and how to use both positive and negative indexing for slicing with examples. Example: Get the items from a list starting at position 1 and ending at position 4 (exclusive). [GFGTABS] Python a = [1, 2, 3, 4, 5, 6
5 min read
Implementing slicing in __getitem__
The __getitem__ method is used for accessing list items, array elements, dictionary entries etc. slice is a constructor in Python that creates slice object to represent set of indices that the range(start, stop, step) specifies. __getitem__ method can be implement in a class, and the behavior of slicing can be defined inside it. Syntax: __getitem__
2 min read
Data Slicing using PyQtGraph
In this article, we will see how we can perform data slicing using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and sec
5 min read
Basic Slicing and Advanced Indexing in NumPy
Indexing a NumPy array means accessing the elements of the NumPy array at the given index. There are two types of indexing in NumPy: basic indexing and advanced indexing. Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data. In this tutorial, we will cover basic slicing and advanced in
5 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
Lexicographically smallest string which is not a subsequence of given string
Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a subsequence. Input: S = "aaaa"Output: aaabExplanat
5 min read
Sum of frequencies of characters of a string present in another string
Given two strings S1 and S2 of lengths M and N respectively, the task is to calculate the sum of the frequencies of the characters of string S1 in the string S2. Examples: Input: S1 = "pPKf", S2 = "KKKttsdppfP"Output: 7Explanation:The character 'p' occurs twice in the string S2.The character 'P' occurs once in the string S2.The character 'K' occurs
5 min read
Check if a string can be repeated to make another string
Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1. Examples: Input: a = "geeks", b = "geeksgeeks" Output: 2 "geeks" can be repeated twice to generate "geeksgeeks" Input: a = "df", b = "dfgrt" Output: -1 Recommended: Please try y
9 min read
Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Python | String startswith()
Python String startswith() method returns True if a string starts with the specified prefix (string). If not, it returns False using Python. Python String startswith() Method SyntaxSyntax: str.startswith(prefix, start, end) Parameters: prefix: prefix ix nothing but a string that needs to be checked.start: Starting position where prefix is needed to
2 min read
Python | Pandas str.join() to join string/list elements with passed delimiter
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg