Write a Python Program to Get a Substring of a String

Substring is a sequence of characters within a larger string.

Python provides built-in string methods that allow us to manipulate strings.

In this tutorial, we will discuss how to get a substring of a string in Python.


To get a substring of a string, we can use slicing.

Slicing is a way to extract a part of a string based on the starting and ending index.

The syntax for slicing is string[start:end].

The start is the index where the slice starts, and the end is the index where the slice ends.

Note that the end index is exclusive, which means the character at the end index is not included in the slice.

Here is an example program that gets a substring of a string:

string = "Hello, World!"
substring = string[0:5]
print(substring)

In this example, we have a string "Hello, World!".

We use slicing to extract the substring "Hello" by specifying the start index as 0 and the end index as 5.

The output of this program is "Hello".

We can also use negative indexing to get a substring.

Negative indexing means counting from the end of the string instead of the beginning.

The index -1 refers to the last character of the string, -2 refers to the second last character, and so on.

Here is an example program that gets a substring using negative indexing:

string = "Hello, World!"
substring = string[-6:-1]
print(substring)

In this example, we use negative indexing to extract the substring "World" by specifying the start index as -6 and the end index as -1.

The output of this program is "World".


In conclusion, getting a substring of a string in Python is a simple task.

We can use slicing to extract a part of the string based on the starting and ending index.

By using negative indexing, we can count from the end of the string to get a substring.