I have the strings '80010', '80030', '80050' in a list, as in
test = ['80010','80030','80050']
How can I delete the very last character (in this case the very last digit of each string which is a 0), so that I can end up with another list containing only the first four digits/characters from each string? So end up with something like
newtest = ['8001', '8003', '8005']
I am very new to Python but I have tried with if-else statements, appending, using indexing [:-1], etc. but nothing seems to work unless I end up deleting all my other zeros. Thank you so much!
Using del Another efficient, yet simple approach to delete the last element of the list is by using the del statement. The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1.
Use the del statement with list slicing to remove the last N elements from a list, e.g. del my_list[len(my_list) - n:] The del statement will remove the last N elements from the original list. Copied!
Method 1: Using list Slicing to Remove the Last Element from the string. The slicing technique can also remove the last element from the string. str[:-1] will remove the last element except for all elements.
test = ["80010","80030","80050"]
newtest = [x[:-1] for x in test]
New test will contain the result ["8001","8003","8005"]
.
[x[:-1] for x in test]
creates a new list (using list comprehension) by looping over each item in test
and putting a modified version into newtest
. The x[:-1]
means to take everything in the string value x up to but not including the last element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With