Python String - Get last N characters
Python String - Get last N characters
To get the last N characters from a string in Python, you can slice the string with negative start index like start=-N. The stop and step for the slice can be left with default.
Or you can specify a start value of length of string minus N.
In this tutorial, you will learn how to get the last N characters from a string in Python using string slicing, with examples.
1. Get last N characters from string using string slicing in Python
If x is the given string, then use the following expression to get the substring with the last n characters from the original string.
x[-n:]
In the following program, we take a string value in variable x, get the last 4 characters, and print it to output.
Python Program
# Input string
x = "Hello, World!"
# Number of characters to retrieve
n = 4
# Get the last n characters
last_n_characters = x[-n:]
# Print the result
print(last_n_characters)
Output
rld!
Related Tutorials
If you would like to use positive index while slicing the string, you may use the following expression to get the last N characters from the string in x.
x[len(x)-n:]
Python Program
# Input string
x = "Hello, World!"
# Number of characters to retrieve
n = 4
# Get the last n characters
last_n_characters = x[len(x) - n:]
# Print the result
print(last_n_characters)
Output
rld!
Summary
In this tutorial, we learned how to get the last N character from a string using string slicing, with the help of examples.