简体   繁体   English

如何删除列表中最后一个元素后的空格

[英]How to remove space after last element in list

list = [1, 2, 3, 4]

for element in list:
    print(element, end=" ")

For this code, the output is: 1 2 3 4 .对于此代码,output 为: 1 2 3 4 But there is a space after the last element(4).How can I remove only that last space?I tried adding sep=" " before the end=" " but it doesn't work.但是最后一个元素之后有一个空格(4)。我怎样才能只删除最后一个空格?我尝试在 end=" " 之前添加 sep=" " 但它不起作用。

You could just use join here:你可以在这里使用join

values = [1, 2, 3, 4]
output = ' '.join([str(x) for x in values])
print(output)  # 1 2 3 4

This would also work.这也行。

lst = [1, 2, 3, 4]
for element in lst:
    if element == lst[len(lst)-1]:
      print(element)
    else:
      print(element, end=" ")

You can print the first n-1 elements with space and then print the last element separately.您可以使用空格打印前 n-1 个元素,然后单独打印最后一个元素。

l = [1, 2, 3, 4]
for i in l[:-1]:
    print(i, end=" ")
print(l[-1], end="")

The easiest solution would be to print everything, but the last element with space, then print the last without a space:最简单的解决方案是打印所有内容,但最后一个元素带有空格,然后打印最后一个不带空格的元素:

lst = [1, 2, 3, 4]

for i in range(len(lst) - 1):
    print(lst[i], end=" ")

print(lst[len(lst) - 1])

The simplest way is:最简单的方法是:

print(*lst)

* operator is for unpacking, it passes individual list items to the print function like print(1, 2, 3, 4) . *运算符用于解包,它将单个列表项传递给 print function ,如print(1, 2, 3, 4) print function use default " " space for the separator. print function 使用默认的" "空间作为分隔符。

note : Internally print calls __str__ method of the elements, I mean it convert it to the string.注意:内部print调用元素的__str__方法,我的意思是将其转换为字符串。

Also don't forget to not using built-in names like list .也不要忘记不使用像list这样的内置名称。

You can print the list by converting it into a list and then use join()您可以通过将列表转换为列表来打印列表,然后使用join()

my_list = [1,2,3,4] # Don't use keywords for naming variables (it is a bad practice)
my_list = [str(x) for x in my_list]
print(' '.join(my_list))

If you want a longer solution then如果您想要更长的解决方案,那么

my_list = [1,2,3,4]
for i in range(len(my_list)):
    if i != len(my_list)-1:
        print(str(my_list[i]) + " ", end='')
    else:
        print(str(my_list[i]), end='')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM