如何从字符串列表中的每个字符串中删除最后一个字符

18

我在列表中有字符串'80010'、'80030'、'80050',如下:

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

如何删除最后一个字符(在这种情况下是每个字符串的最后一个数字0),以便我最终可以得到另一个只包含每个字符串的前四个数字/字符的列表?因此最终得到类似以下内容:

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

我对Python非常陌生,但是我已经尝试过if-else语句、添加内容以及使用索引[:-1]等方法,但除非我删除所有其他的零,否则似乎什么都行不通。非常感谢!

5个回答

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

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

[x[:-1] for x in test]使用列表推导式遍历test中的每个项目并将修改后的版本放入newtest中创建一个新列表。 x[:-1]的意思是取字符串值x中除最后一个元素外的所有内容。


非常好的解释给了我自己 XD - sguan
我使用了你的解决方案,但是它删除了我的列表中每个元素的最后一个字符,而不是删除最后一个元素,我不明白为什么会这样。 - newbie

7

你说得没错。使用切片符号[:-1]是正确的方法。只需要将它与列表推导结合起来:

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

somestring[:-1] 表示从位置 0 开始(包括位置 0)到最后一个字符(不包括最后一个字符)的所有内容。


3

为了展示一种稍微不同于列表推导式的解决方案,鉴于其他答案已经解释了切片方法,我将介绍使用map函数的方法。

使用map函数。

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

如果您想了解更多关于此解决方案的信息,请阅读我在另一个类似问题中提供的简要说明。

将列表转换为字符串三元组序列


2
这在Python 2中有效。如果您使用的是Python 3,则map函数返回一个生成器(按请求每次返回1个项目),因此如果您想要列表,则需要将其包装在列表调用中(list(map(lambda x: x[:-1],test)))。此外,在Python 3中,print表达式变成了一个函数,因此您还必须将要打印的任何内容也放在括号中。 - Matthew

0
在Python中,@Matthew的解决方案是完美的。但如果你确实是一个编程新手,我必须推荐这个方法,虽然不太优雅,但在许多其他情况下是唯一的方法:
#variables declaration
test = ['80010','80030','80050'] 
length = len(test)                 # for reading and writing sakes, len(A): length of A
newtest = [None] * length          # newtest = [none, none, none], go look up empty array creation
strLen = 0                         # temporary storage

#adding in newtest every element of test but spliced
for i in range(0, lenght):         # for loop
    str = test[i]                  # get n th element of test
    strLen = len (str)             # for reading sake, the lenght of string that will be spliced
    newtest[i] = str[0:strLen - 1] # n th element of newtest is the spliced n th element from test

#show the results
print (newtest)                    # ['8001','8003','8005']

附言:尽管这个脚本不是最好的,但它可以在Python中运行!祝任何新手程序员好运。


-1

我曾经遇到过类似的问题,这里是解决方案。

List<String> timeInDays = new ArrayList<>();
timeInDays.add(2d);
timeInDays.add(3d);
timeInDays.add(4d);

我需要删除每个字符串的最后一个字母以进行比较。以下解决方案适用于我。

List<String> trimmedList = new ArrayList<>;
for(int i=0;i<timeInDays.size();i++)
{
String trimmedString = timeInDays.get(i).substring(0,name.length()-1);
trimmedList=add(trimmedString );
}

System.out.println("List after trimming every string is "+trimmedList);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接