How do I get a substring from a string in Python?

To get a substring from a string in Python, you can use the slicing operator string[start:end:step]. The slice operator returns the part of a string between the "start" and "end" indices. The "step" parameter specifies how many characters to advance after extracting the first character from the string. Besides the slice operator, you can get a substring from a string using the Regular Expressions (re). In this Python Substring Example, we use the slicing operator to get a substring from the provided string. Below you can see an example of getting a substring using Regular Expressions. Click Execute to run Python Substring Example online and see the result.
How do I get a substring from a string in Python? Execute
text = 'Python is easy to learn and use.'

substring = text[9:23]

print(substring)
Updated: Viewed: 1058 times

Python Slice Operator Syntax

To get a substring from a string using the slice method, you can use the following syntax:

Python Syntax of String Slicing
string[start: end: step]

Where:
  • start: the starting index of the substring. The value at this index is included in the substring. If no start is specified, it should be 0.
  • end: the ending index of the substring. The value at this index is not included in the substring. If no end is specified or the specified value exceeds the length of the string, it defaults to the length of the string.
  • step: every step character after the current character must be included. If the step value is omitted, it is assumed to default to 1. When you pass a step value of -1 and omit the start and end values, the slice operator reverses the string.

Python Substring Templates

  1. string[start:end] - the syntax for getting all characters from the start of the index to the end of -1
  2. string[:end] - the syntax for getting all characters from the beginning of the line to the end of -1
  3. string[start:] - the syntax for getting all characters from the start of the index to the end of the string
  4. string[start:end:step] - the syntax to get all characters from start to end -1 at a discount per step character

How to extract a substring using a regular expression in Python?

Regular expressions are a powerful string manipulation tool in Python that is natively supported in Python. To extract a substring from a string using regular expressions, you must first import the "re" module into your code. The re.search() method takes a regular expression pattern as its first parameter and a string as its second parameter and returns the matching portion of the string as its result. In the Python substring example below, the re.search() method returns the substring in the group at index 1.

Example of Extracting a Substring using a Regular Expression
import re

text = 'Python is easy to learn and use.'
      
m = re.search('is(.+?)and', text)

print(m.group(1))

# output: easy to learn 

See also