How to Substring a String in Python?

Posted in /   /  

How to Substring a String in Python?
vinaykhatri

Vinay Khatri
Last updated on November 24, 2024

    In Python, the string is a sequence of Unicode characters, represented within the single or double quotes. A string can contain any character, including alphanumeric and special symbols. In this tutorial, we will learn how to extract a substring from a string in Python. Also, we will know the different methods that we can use to extract a substring from a string.

    What is a Substring in Python?

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

    String Slicing in Python

    In Python, to access a string, we use the variable name of the string. By only using the variable name, we can 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 starts from 0.

    Code 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

    1. 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. Code Example

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

    Output

    world techgeekbuzz 

    2) Slice a Python String Without Specifying the Starting Index String[:EndIndex]

    If we do not specify the starting index while slicing the string, then the starting index becomes 0 by default.

    Code Example

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

    Output

    hello

    3. Slice a Python String Without Specifying the Starting and Ending Index Values string[:]

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

    Code Example

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

    Output

    hello world techgeekbuzz

    4. String Slicing With Steps

    By far, we only discussed how we could specify the starting and ending index values during slicing to get a substring. But slicing also supports step value, which describes 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 the starting index to the end index. And its value could be any integer number except 0.

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

    Code Example

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

    Output

    hlowrdtcgebz

    6. Reverse a String Using Slicing in Python

    A string can be reversed using slicing in Python . By setting the step value to -1 and leaving the startIndex and endIndex blank, the string will be reversed. The -1 represents that the count should be negative and 1 step at a time.

    Code Example

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

    Find All The Possible Substrings of a String in Python

    To find all the possible substrings of a string in Python, we have to create a nested for loop.

    Code Example

    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 is also a substring.

    Find All the Possible Substrings of a String in Python using List Comprehension

    Python list comprehension provides an alternative to creating a list of elements using for loop within a single line. Here is an example of finding all the possible substrings of a string using list comprehension. Code Example

    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', ''}

    How to Check If a String is a Substring?

    To check if a string is a substring of another string, we can use the in operator. The Python operator checks if the string is a substring and returns True. Else, it returns False.

    Code 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 the in operator. A substring in Python is also known as string slicing, and most of the time, you will be hearing and using the word slicing.

    People are also reading:

    Leave a Comment on this Post

    0 Comments