Get a Substring of a String in Python

Get a Substring of a String in Python

Minahil Noor Dec-10, 2020 Oct-22, 2020 Python Python String

This article will introduce a method to get a substring of a string using Python code, that is, the string slicing method.

Use the string slicing method to get the substring of a string in Python

Python doesn’t have any special function to get a substring of a string. However, we can use the string slicing method to achieve this. We treat a string as an array of characters in Python. Using this concept, we can slice out our required substring from an existing string. The correct syntax to use this method is as follows:

stringName[start:end:step]

The detail of this method is as follows:

Parameters Description
start optional It is the starting point of our substring. If omitted, then the substring starts from the start of the given string.
end optional It is the ending point of our substring. If omitted, then the substring ends where our string ends.
step optional It tells about the skipping of any character. If it is 2, then after one character, one character will be skipped.

The program below shows how we can use this method to get a substring of a string in Python.

string = "This is my string"
print(string[5:11])

Output:

is my

We have sliced out characters from index 5 to 11.

Let’s see the result if we pass nothing.

string = "This is my string"
print(string[::])

Output:

This is my string

Now, if we also pass the stepping element, then the output will be as follows:

string = "This is my string"
print(string[5:11:2])

Output:

i y

From index 5 to 11, after one character, one character is skipped.

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python