How to Substring a String in Python

By | April 12, 2021
How to Substring a String in Python

In Python the string is a Sequence of unicode characters, represented within the single or double quotation. A string can contain any character including alphanumeric and special symbols. In this tutorial we will learn how to substring a string in Python, and what are the different methods we can use to substring a string.

What is a Substring in Python?

A substring is a sequential part of string itself. If a string a present in string b then string a would be considered as a sub string of b.  And in Python this substring is also referred to a Python string slicing.

Vamware

String Slicing in Python

In Python, to access a string we use the string variable name. By only using the variable name we get the complete string, but if we want to retrieve a part, or a specific character from the string then we use indexing and slicing.

In Slicing we use index values of a given string to grab a sequence of characters from the string.

sub_string = string[ strartIndex : endIndex]

Note: The index value start from 0

Example

string = "Hello World It's TechGeekBuzz"

sub_string_1 = string[0:5]

print("The Sub String 1 is:", sub_string_1)

print("The Sub String 2 is:", sub_string_2)

Output

The Sub String 1 is: Hello
The Sub String 2 is: World It's TechGeekBuzz 

More Examples on Python Sub Strings

Slice a Python string without using the end-index  string[StartIndex:]  

If we do not specify the end index value then it would be treated as the last index value.

string = "hello world techgeekbuzz"

sub_string = string[5:]

print(sub_string)

Output

 world techgeekbuzz 

Slice a Python String without specifying the Starting index string[:EndIndex]

If we do not specify the starting indexing while slicing the string then start index become 0 by default.

string = "hello world techgeekbuzz"
sub_string = string[:5]
print(sub_string)

Output

hello

Slice a Python String without specifying the Starting and Ending Index value string[:]

If we do not specify the starting and ending index values for the slicing, then the slicing return the complete string from index value 0 to the (n-1) n is the length of string.

string = "hello world techgeekbuzz"
sub_string = string[:]
print(sub_string)

Output

hello world techgeekbuzz

String Slicing with steps

By far we only discuss how can we specify the starting and ending index value during slicing to get a sub string. But slicing also support step value, which describe in what sequence the substring should be retrieved from a string. And the step value is the last part of the slicing.

Syntax

slice = string[ startIndex: endIndex: steps]

<Note>: By default, the step value is 1, which signifies that the step count should be +1 from start index to end index. And its value could be any integer number except 0.

Slice a Python Sting with step count 2

If the step value is 2 then the string slice will skip every consecutive value and grab the alternative one.

string = "hello world techgeekbuzz"
slice = string[::2]
print(slice)

Output

hlowrdtcgebz

Reverse a String using Slicing in Python

A string can be reverse using slicing. By setting the step value to -1 and leaving the startIndex & endIndex to blank the sting will be reversed. Check here the example of reverse a string in python.

The -1 represent that the count should be in negative and 1 step at a time.

Example

>>>string = "hello world techgeekbuzz"
>>> reverse = string[ : : -1]
>>> print(reverse)
zzubkeeghcet dlrow olleh

Find all the Possible Substring of a String in Python

To find all the possible sub string of a python we have to create a nested for loop.

string ="python"

all_sub_strings =set()

for i in range(len(string)):
    for j in range(i, len(string)):
        all_sub_strings.add(string[i:j])
print(all_sub_strings)

Output

{'', 'yt', 'ytho', 'y', 'yth', 't', 'ho', 'pytho', 'o', 'pyt', 'pyth', 'p', 'py', 'th', 'h', 'tho'}

<Note>: An empty string also a sub string. 

Find all the Possible Substring of a String in Python using List Comprehension

Python List comprehension provide an alternative to create list of elements using for loops with in a single line.

Here is the example of finding all the possible substring of a string using list comprehension.

string = "python"
sub_strings = [string[i:j] for i in range(len(string)) for j in range(i,len(string))]
print(set(sub_strings))

Output

{'pytho', 'pyt', 'ytho', 'y', 'tho', 'th', 't', 'pyth', 'h', 'yt', 'yth', 'py', 'p', 'ho', 'o', ''}

Check if a string is a substring

To check if a string is a substring of another string, we can use the python in operator.

The in operator check if the string is a substring and return True, else it return False.

Example

string = "python"
>>> "p" in string
True
>>> "pytho" in string
True
>>> "" in string
True
>>> "on" in string
True
>>> "hell" in string
False

Summary

In this tutorial you learned all about how to substring a string in python. You also learned how to find all the possible substrings for a string and how to check if a string is a substring or not using in operator. Substring in Python also known as string slicing and most of the time you will be hearing and using the word slicing.

Leave a Reply

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