Python Program to Get a Substring of a String Ad Sponsored

ⓘ Sponsored by

A substring is a sequence of characters that is part of a longer string. In other words, a substring is a smaller string that occurs within a larger string. For example, in the string “Hello world”, “Hello”, “world”, “lo”, and “l” are all substrings of the original string.

Python Code :

The below Python program gets a substring of a string:

# Define a string
my_string = "Hello, World!"

# Get a substring of the string
substring = my_string[7:12]

# Print the substring
print("The substring is:", substring)

In this program, we define a string called my_string containing some text. We then use slicing to get a substring of the string, starting at index 7 (which corresponds to the letter “W” in “World”) and ending at index 12 (which corresponds to the letter “d” in “World”). The substring is then stored in the variable substring. Finally, we print the substring using the print() function.

Note that in Python, string indices start at 0. So the first character of a string is at index 0, the second character is at index 1, and so on. When using slicing, the first index is inclusive (i.e., the character at that index is included in the substring), and the second index is exclusive (i.e., the character at that index is not included in the substring).

You can adjust the starting and ending indices to get different substrings of the string. For example, to get the first three characters of the string, you can use my_string[0:3]. To get the last four characters of the string, you can use my_string[-4:], which includes all characters from the fourth-last character to the end of the string. Ad Sponsored

ⓘ Sponsored by