Get a Substring of a String in Python

(Last Updated On: 02/03/2023)

Python Program to Get a Substring of a String

#Get a Substring of a String in python

my_string = "Welcome to Newtum."

# prints "Welcome"
print(my_string[:7])

# prints "to"
# You need to specify the starting index and the ending index of the substring. In this case, love starts at index 8 and ends at index 10.
print(my_string[8:10])

# prints "to"
#All the text from index 11 to the end are selected.
print(my_string[11:])

# prints "I love python"
#All the text before the last index is selected.
print(my_string[:-1])

Output:

Welcome
to
Newtum.
Welcome to Newtum

Leave a Reply

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