In this article, I will discuss how to remove the last number of characters from a string using Python.
As strings are iterable, you can use index and slice methods to access the individual or group of characters within the strings.
Using string slices
In slice, the first character of the string starts with 0 and the last character of the string starts with -1 (equivalent to len(string) - 1).
Remove the last character in a string using a negative index,
x = 'ATGCATTTC' # # Remove last character x[:-1] 'ATGCATTT' # Remove last 2 characters x[:-2] 'ATGCATT'
Remove the last character in a string using a positive index,
x[:len(x)-1] # Note: -1 is equivalent len(x)-1 'ATGCATTT' # Remove last 2 characters x[:len(x)-2] 'ATGCATT'
If you know the last character of a string, you can use the
You can also remove special characters such as whitespace using
y = 'ATGCATTTC ' y.rstrip() 'ATGCATTTC'
Strings can be converted to a list to remove the last character in a string
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 firstname.lastname@example.org
This work is licensed under a Creative Commons Attribution 4.0 International License