How to remove the last character from each line in a list of strings

I have the lines "80010", "80030", "80050" in the list, as in

test = ['80010','80030','80050'] 

How can I remove the last character (in this case the very last digit of each line that is 0) so that I can end up with another list containing only the first four digits / characters from each line? It so happened something like

 newtest = ['8001', '8003', '8005'] 

I am very new to Python, but I tried with if-else statements, adding using indexing [: -1] etc., but nothing works unless I delete all other zeros. Thank you very much!

+6
source share
3 answers
 test = ["80010","80030","80050"] newtest = [x[:-1] for x in test] 

The new test will contain the result ["8001","8003","8005"] .

[x[:-1] for x in test] creates a new list (using list comprehension), newtest over each item in test and placing the modified version in newtest . x[:-1] means that all values โ€‹โ€‹of the string x do not exceed, but not including the last element.

+7
source

You are not that far. Using slice notation [: -1] is the right approach. Just connect it to the list:

 >>> test = ['80010','80030','80050'] >>> [x[:-1] for x in test] ['8001', '8003', '8005'] 

somestring[:-1] gives you everything from a character at position 0 (inclusive) to the last character (excluding).

+6
source

Just to show a slightly different solution besides understanding, Given that the other answers have already explained the slicing, I'm just looking at the method.

With display function.

 test = ['80010','80030','80050'] print map(lambda x: x[:-1],test) # ['8001', '8003', '8005'] 

For more information about this solution, please read the brief explanation I made in another similar question.

Convert a list to a sequence of strings of triples

+1
source

All Articles