Open In App

How to Substring a String in Python

Last Updated : 02 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
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”.

Python3




# 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!”.

Python3




# 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”.

Python3




# 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

Python3




# 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.

Python3




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


Output

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads