Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Get the string after occurrence of given substring
Next article icon

Python | Get the substring from given string using list slicing

Last Updated : 26 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 slicing

Syntax: myString[start:stop:step]

Parameter:

  • start: It is the index of the list where slicing starts.
  • stop: It is the index of the list where slicing ends.
  • step: It allows you to select nth item within the range start to stop.

Example 1: In this example, we will see how to take a substring from the end or from starting of the string. 

Python3




# Python3 code to demonstrate
# to create a substring from a string
 
# Initialising string
ini_string = 'xbzefdgstb'
 
# printing initial string and character
print("initial_strings : ", ini_string)
 
# creating substring from start of string
# define length upto which substring required
sstring_strt = ini_string[:2]
sstring_end = ini_string[3:]
 
# printing result
print("print resultant substring from start", sstring_strt)
print("print resultant substring from end", sstring_end)
 
 

Output:

initial_strings :  xbzefdgstb print resultant substring from start xb print resultant substring from end efdgstb

Example 2: In this example, we will see how to create a string by taking characters from a certain positional gap. 

Python3




# Python3 code to demonstrate
# to create a substring from string
 
# Initialising string
ini_string = 'xbzefdgstb'
 
# printing initial string and character
print("initial_strings : ", ini_string)
 
# creating substring by taking element
# after certain position gap
# define length upto which substring required
sstring_alt = ini_string[::2]
sstring_gap2 = ini_string[::3]
 
# printing result
print("print resultant substring from start", sstring_alt)
print("print resultant substring from end", sstring_gap2)
 
 

Output:

initial_strings :  xbzefdgstb print resultant substring from start xzfgt print resultant substring from end xegb

Example 3: In this example, we are considering both cases of taking strings from the middle with some positional gap between characters. 

Python3




# Python3 code to demonstrate
# to create a substring from string
 
# Initialising string
ini_string = 'xbzefdgstb'
 
# printing initial string and character
print ("initial_strings : ", ini_string)
 
# creating substring by taking element
# after certain position gap
# in defined length
sstring = ini_string[2:7:2]
 
# printing result
print ("print resultant substring", sstring)
 
 

Output:

initial_strings :  xbzefdgstb print resultant substring zfg

Approach #4: Using list slicing to get substrings from a given string:

Approach:

 Step size of 1 (no skipping):
This approach selects every character within the specified range of the string.

Step size of 2 (select every other item):
This approach selects every other character within the specified range of the string.

Step size of 3 (select every third item):
This approach selects every third character within the specified range of the string.

Step size of -1 (reverse order):
This approach selects every character within the specified range of the string in reverse order.

Step size of -2 (reverse order, select every other item):
This approach selects every other character within the specified range of the string in reverse order.

Step size of -3 (reverse order, select every third item):
This approach selects every third character within the specified range of the string in reverse order.

Python3




# Example 1: Get the first 3 characters of a string
myString = "Hello World"
substring = myString[0:3]
print(substring)  # Output: "Hel"
 
# Example 2: Get every other character in a string
myString = "abcdefghijklmnopqrstuvwxyz"
substring = myString[0:len(myString):2]
print(substring)  # Output: "acegikmoqsuwy"
 
# Example 3: Get a substring starting from the 4th character and skipping every third character
myString = "abcdefghijklmnopqrstuvwxyz"
substring = myString[3:len(myString):3]
print(substring)  # Output: "dgljmpsvy"
 
 
Output
Hel acegikmoqsuwy dgjmpsvy

When the step size is 1 (i.e., no skipping), list slicing has a time complexity of O(stop-start) and a space complexity of O(stop-start), since it creates a new list containing the sliced elements.
When the step size is greater than 1, the time complexity of list slicing depends on the size of the sliced substring, since it only creates a new list containing the selected elements

. The space complexity is O(stop-start/step), since it only creates a new list containing a fraction of the original elements.
Using a negative step size allows you to slice the string in reverse order. The time and space complexity are the same as for a positive step size.



Next Article
Python | Get the string after occurrence of given substring
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Remove the given substring from end of string
    Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Remove the substring from the end of the string using Slicing In thi
    3 min read
  • Python - Get all substrings of given string
    A substring is any contiguous sequence of characters within the string. We'll discuss various methods to extract this substring from a given string by using a simple approach. Using List Comprehension :List comprehension offers a concise way to create lists by applying an expression to each element
    3 min read
  • Finding Strings with Given Substring in List - Python
    The task of finding strings with a given substring in a list in Python involves checking whether a specific substring exists within any of the strings in a list. The goal is to efficiently determine if the desired substring is present in any of the elements of the list. For example, given a list a =
    3 min read
  • Python | Get the string after occurrence of given substring
    The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python. Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
    3 min read
  • Python program to split a string by the given list of strings
    Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
    4 min read
  • Python - Find all the strings that are substrings to the given list of strings
    Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation
    5 min read
  • Python | Splitting string list by strings
    Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let's discuss certain way to solv
    3 min read
  • Python - Remove substring list from String
    In Python Strings we encounter problems where we need to remove a substring from a string. However, in some cases, we need to handle a list of substrings to be removed, ensuring the string is adjusted accordingly. Using String Replace in a LoopThis method iterates through the list of substrings and
    3 min read
  • Python | Get the starting index for all occurrences of given substring
    Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in #
    3 min read
  • Python | Frequency of substring in given string
    Finding a substring in a string has been dealt with in many ways. But sometimes, we are just interested to know how many times a particular substring occurs in a string. Let's discuss certain ways in which this task is performed. Method #1: Using count() This is a quite straightforward method in whi
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences