In this article, I will discuss how to get the last any number of characters from a string using Python
Using numeric index
The numeric string index in Python is zero-based i.e., the first character of the string starts with 0. If you know the length of the string, you can easily get the last character of the string
Get last character using positive index
x = 'ATGCATTTC' x[len(x)-1] 'C'
Get the last character using negative index (the last character starts at -1)
x = 'ATGCATTTC' x[-1] 'C'
Using string slices
Get the last character in a string,
x[len(x)-1:] 'C' # using negative index x[-1:] 'C'
Get the last few character in a string,
# get last 2 characters x[len(x)-2:] 'TC' # using negative index x[-2:] 'TC'
Strings can be converted to lists to access the individual characters in a string
# get last character list(x)[-1] 'C'
Learn more about Python
- Python enumerate
- Python tuples
- 8 different ways to get column names from pandas DataFrame
- 4 different ways to rename column names in pandas DataFrame
If you have any questions, comments or recommendations, please email me at email@example.com
This work is licensed under a Creative Commons Attribution 4.0 International License