Skip to content

Python extract substring from string

  • by

Extracting substrings from a string in Python means obtaining a smaller sequence of characters (substring) from a given string. Python provides several methods to achieve this, including slicing, string methods, and regular expressions.

Python extracts a substring from a string

Here are some examples of extracting substrings from a string using different methods in Python:

1. Using Slicing: Slicing involves extracting a portion of the string based on its index positions. The syntax for slicing is string[start_index:end_index], where start_index is the index of the first character to include in the substring, and end_index is the index of the first character not to include in the substring.

# Example string
text = "Hello, World!"

# Extract substring from index 0 to 4 (exclusive)
substring = text[0:5]
print(substring)  # Output: "Hello"

2. Using String Methods: Python has built-in string methods that can be used to extract substrings based on specific patterns. Some common methods are split(), find(), startswith(), endswith(), etc.

# Example string
text = "Hello, World!"

# Using split() to extract a substring based on a delimiter (comma in this case)
substring = text.split(',')[0]
print(substring)  # Output: "Hello"

# Using find() and slicing to extract a substring between two characters
start_index = text.find('H')
end_index = text.find('!')
substring = text[start_index:end_index+1]
print(substring)  # Output: "Hello, World"

3. Using Regular Expressions (Regex): Regular expressions provide a powerful way to extract substrings based on more complex patterns.

import re

# Example string
text = "Hello, World!"

# Using regex to extract all capitalized words
matches = re.findall(r'\b[A-Z][a-z]*\b', text)
print(matches)  # Output: ['Hello', 'World']


Python extract substring from string

These are some of the methods available in Python to extract substrings from a string. The choice of method depends on the specific requirements and patterns present in the string you are working with.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *