Categories
Python Answers

How to get a substring of a string in Python?

Spread the love

Sometimes, we want to get a substring of a string in Python.

In this article, we’ll look at how to get a substring of a string in Python.

How to get a substring of a string in Python?

To get a substring of a string in Python, we can use the MyString[a:b] syntax, where MyString is a string and a and b are the start and end indexes.

The substring between a and b - l will be returned.

For instance, we write:

x = "Hello World!"
y = x[2:-2]
print(y)

to return a substring of x between index 2 and -2 exclusively.

Therefore, the substring will have the 3rd character to the 3rd last character.

Therefore, y is 'llo Worl'.

Conclusion

To get a substring of a string in Python, we can use the MyString[a:b] syntax, where MyString is a string and a and b are the start and end indexes.

The substring between a and b - l will be returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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