如何从字符串列表中的每个字符串中删除最后一个字符 [英] How to delete the very last character from every string in a list of strings

查看:135
本文介绍了如何从字符串列表中的每个字符串中删除最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表中有字符串"80010","80030","80050",如

I have the strings '80010', '80030', '80050' in a list, as in

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

如何删除最后一个字符(在这种情况下,每个字符串的最后一个数字为0),这样我才能得到另一个仅包含每个字符串的前四位数字/字符的列表.所以最后得到

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']

我对Python非常陌生,但是我尝试使用if-else语句,追加,使用索引[:-1]等,但是除非最终删除所有其他零,否则似乎没有任何效果.非常感谢!

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!

推荐答案

test = ["80010","80030","80050"]
newtest = [x[:-1] for x in test]

新测试将包含结果["8001","8003","8005"].

[x[:-1] for x in test]通过遍历test中的每个项目并将修改后的版本放入newtest中来创建新列表(使用 list理解). x[:-1]表示将字符串值x中的所有内容取为最大值,但不包括最后一个元素.

[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.

这篇关于如何从字符串列表中的每个字符串中删除最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆