W3docs

How do I get a substring of a string in Python?

To get a substring of a string in Python, you can use the string[start:end] notation.

To get a substring of a string in Python, you can use the string[start:end] notation. This will return a new string that is a copy of the original string, starting from the character at the start index and going up to, but not including, the character at the end index.

For example:

Get a substring of a string in Python using integer ranges in a brucket

python— editable, runs on the server

This will output the following string:


world

You can also omit the start or end index to specify the beginning or end of the string, respectively. For example:

Get a substring of a string in Python without specifying the beginning or the end

python— editable, runs on the server

The first example will output Hello, and the second example will output world!.

You can also use negative indices to specify the position of a character relative to the end of the string. For example, -1 refers to the last character in the string, -2 refers to the second-to-last character, and so on.

For example:

Get a substring of a string in Python with negative indices

python— editable, runs on the server

This will output world!.