Menu Close

How to get a substring of a string in Python?

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 slice syntax.

For instance, we write

y = x[2:-2]

to get the substring from string x from index 2 to the 2nd last character in the string.

We can also skip the start or end indexes.

For instance, we write

y = x[2:]

to get the character at index 2 to the end of the string.

And we write

x[:-2]

to get the character at index 0 to the 2nd last character of the string.

Conclusion

To get a substring of a string in Python, we can use the slice syntax.

Posted in Python, Python Answers