Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中删除列表项末尾的空格_Python_Python 3.x_List - Fatal编程技术网

在python中删除列表项末尾的空格

在python中删除列表项末尾的空格,python,python-3.x,list,Python,Python 3.x,List,我有以下列表,我想删除列表项末尾的空格, 仅从末尾开始,而不是所有空格 items = [' apple ', 'banana ', 'orange '] 只需创建一个新列表并使用列表理解。 遍历每个元素,检查元素末尾是否有空格。 如果有,请将其删除并附加到新列表中 items = [' apple ', 'banana ', 'orange '] newList = [x[:-1] for x in items if x[-1] == ' '] print(newList) 输出 [' a

我有以下列表,我想删除列表项末尾的空格, 仅从末尾开始,而不是所有空格

items = [' apple ', 'banana ', 'orange ']

只需创建一个新列表并使用列表理解。 遍历每个元素,检查元素末尾是否有空格。 如果有,请将其删除并附加到新列表中

items = [' apple ', 'banana ', 'orange ']
newList = [x[:-1] for x in items if x[-1] == ' ']
print(newList)
输出

[' apple', 'banana', 'orange']

您可以将列表理解用于
rstrip()

items=[‘苹果’、‘香蕉’、‘橘子’]
输出=[x.rstrip()用于项目中的x]
打印(输出)#[‘苹果’、‘香蕉’、‘橙色’]

这可能是OP想要的,因为它删除了结尾的所有空格,而不仅仅是一个空格字符。但我要求澄清一下,以防万一。出于兴趣,如果字符串以两个空格结尾,您希望发生什么?你想让他们两个都走,还是只剩下第二个?它只是空格,还是全部空白(制表符等)?