简体   繁体   中英

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

You could just use join here:

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.

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 use default " " space for the separator.

note : Internally print calls __str__ method of the elements, I mean it convert it to the string.

Also don't forget to not using built-in names like list .

You can print the list by converting it into a list and then use 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='')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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