Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the very last character from every string in a list of strings

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!

like image 245
spartmar Avatar asked Jan 19 '16 00:01

spartmar


People also ask

How do I remove the last element from a list?

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.

How do you remove the last 4 elements of a list?

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!

How do you remove the last character of a string in Python?

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.


1 Answers

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.

like image 160
Matthew Avatar answered Nov 12 '22 20:11

Matthew