How to Slice a String from the End in Python?

Estimated read time 2 min read

To slice a string from the end in Python, you can use negative index values in the slice notation. Negative index values start from the end of the string with -1 being the index of the last character, -2 being the index of the second-last character, and so on.

Here’s an example of slicing a string from the end:

my_string = "Hello, World!"
# slice the last 6 characters
new_string = my_string[-6:]
print(new_string) # Output: World!

In this example, the slice starts from the second-last character (-6) and goes up to the end of the string. The resulting slice is a new string containing the last 6 characters of the original string: “World!”.

You can also use negative index values for the starting index of the slice to specify the number of characters from the end of the string that you want to include in the slice. For example:

my_string = "Hello, World!"
# slice the last 6 characters
new_string = my_string[-6:len(my_string)]
print(new_string) # Output: World!

In this example, the slice starts from the index corresponding to the length of the string (len(my_string)), minus 6 characters (-6), and goes up to the end of the string. The resulting slice is the same as the previous example: “World!”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply