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:
How to Index and Slice Strings in Python?
Next article icon

How to Substring a String in Python

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a string in Python.

Substring a string in Python

  • Using String Slicing
  • Using str.split() function
  • Using Regular Expressions

Using String Slicing to get the Substring

Consider the string " GeeksForGeeks is best! ". Let's perform various string-slicing operations to extract various substrings

Extracting a Substring from the Beginning

In this example, we are trying to extract the starting word from the string.we used string slicing to extract the substring "Geeks" from the beginning of the string. The slice notation str[:5] starts at index 0 (the first character) and goes up to, but does not include, index 5, resulting in "Geeks".

Python
# code str = "GeeksForGeeks is best!" substring_start = str[:5] print(substring_start) 

Output

Geeks

Extracting the Last Portion of the String

In this example we are trying to extract the last portion of the string.we used string slicing to extract the substring "best!". By omitting the end index, the slice extends to the end of the string, resulting in "best!".

Python
# code str = "GeeksForGeeks is best!" substring_last = str[17:] print(substring_last) 

Output

best!

Extracting a Substring from the Middle

In this example we are trying to extract the middle portion of the string.In this example, we specified both the start and end indices to extract the substring "is" from the text. The slice notation text[14:16] starts at index 14 and goes up to, but does not include, index 16, resulting in "is".

Python
# code str = "GeeksForGeeks is best!" substring = str[14:16] print(substring) 

Output

is

Using str.split() function

We can use the split() function to get the substrings.The split() method effectively splits the string "Geeks For Geeks" into words based on spaces. So, the resulting substrings list contains each word as an element

Python
# code str="Geeks For Geeks" substrings=str.split() print(substrings) 

Output

['Geeks', 'For', 'Geeks']

Using Regular Expressions

We can use re.findall() method to find all the substrings with the regular expressions.we have used the regular expression 'w+' which matches one or more word characters. We then used re.findall() function to get all the strings based on the regular expression specified. The resulting output is individual words as substrings.

Python
import re str = "GeeksforGeeks is best!" pattern = r'\w+' substrings = re.findall(pattern, str) print(substrings) 

Output

['GeeksforGeeks', 'is', 'best']

Next Article
How to Index and Slice Strings in Python?

M

magichat
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • How to reverse a String in Python
    Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Let’s see how it works: Using string slicingThis slicing method is one of the
    4 min read
  • How to Index and Slice Strings in Python?
    In Python, indexing and slicing are techniques used to access specific characters or parts of a string. Indexing means referring to an element of an iterable by its position whereas slicing is a feature that enables accessing parts of the sequence. Table of Content Indexing Strings in PythonAccessin
    2 min read
  • String Subsequence and Substring in Python
    Subsequence and Substring both are parts of the given String with some differences between them. Both of them are made using the characters in the given String only. The difference between them is that the Substring is the contiguous part of the string and the Subsequence is the non-contiguous part
    5 min read
  • Check if String Contains Substring in Python
    This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
    8 min read
  • Python - Check if substring present in string
    The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check. Using in operatorThis
    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 P
    10 min read
  • String Slicing in Python
    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: [GFGTABS] Python s = "Hello, Python!" print(s[0:5]) [/GFGTABS]OutputHello Ex
    4 min read
  • Convert string to title case in Python
    In this article, we will see how to convert the string to a title case in Python. The str.title() method capitalizes the first letter of every word. [GFGTABS] Python s = "geeks for geeks" result = s.title() print(result) [/GFGTABS]OutputGeeks For Geeks Explanation: The s.title() method con
    2 min read
  • replace() in Python to replace a substring
    replace() method in Python allows us to replace a specific part of a string with a new value. It returns a new string with the change without modifying the original one. We can also specify how many times the replacement should occur. For Example: [GFGTABS] Python s = "hlo AB world" # Repl
    2 min read
  • Python String strip() Method
    strip() method in Python removes all leading and trailing whitespace by default. You can also specify a set of characters to remove from both ends. It returns a new string and does not modify the original. Let's take an example to remove whitespace from both ends of a string. [GFGTABS] Python s =
    2 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