在 Python 中打印以空格分隔的元素列表

在 Python 中打印以空格分隔的元素列表

Print a list of space-separated elements in Python

使用sep参数打印以空格分隔的元素列表,例如
print(*my_list, sep=' '). 列表中的项目将在print()函数调用中解包,并将打印在一行中,以空格分隔。

主程序
my_list = ['bobby', 'hadz', 'com'] print(*my_list, sep=' ') # 👉️ bobby hadz com print(*my_list, sep=', ') # 👉️ bobby, hadz, com # ------------------------------------------ var1 = 'bobby' var2 = 'hadz' for item in [var1, var2]: print(item, end=' ') # 👉️ bobby hadz # ------------------------------------------- # 👇️ using str.join() result = ' '.join([var1, var2]) print(result) # 👉️ bobby hadz

在打印列表时,我们使用sep参数用空格分隔列表的元素。

请注意,我们在对 的调用中使用了可迭代解包*运算符来解包列表项print()

*迭代解包运算符
使我们能够在函数调用、推导式和生成器表达式中解包可迭代对象。

sep参数是我们传递给 的参数之间的分隔print()

主程序
print('bobby', 'hadz', sep='') # 👉️ bobbyhadz print('bobby', 'hadz') # 👉️ bobby hadz

默认情况下,sep参数设置为空格。

print()函数还接受一个end参数。

主程序
for item in ['bobby', 'hadz']: # bobby # hadz print(item) for item in ['bobby', 'hadz']: # bobby hadz print(item, end=' ')

默认情况下,end设置为换行符 ( \n)。

我们将end参数设置为空格,以用空格而不是换行符分隔值\n

或者,您可以使用该str.join()方法。

使用 str.join() 打印以空格分隔的元素列表

要打印以空格分隔的元素列表:

  1. Use the str.join() method to join the list into a string with a space
    separator.
  2. If the list contains numbers, convert them to strings.
  3. Use the print() function to print the string.
main.py
list_of_strings = ['bobby', 'hadz', '.com'] result = ' '.join(list_of_strings) print(result) # 👉️ bobby hadz .com # --------------------------------------------- list_of_numbers = [55, 10, 44] result = ' '.join(str(item) for item in list_of_numbers) print(result) # 👉️ 55 10 44

The str.join method
takes an iterable as an argument and returns a string which is the concatenation
of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your list contains numbers or other types, convert all of the values to
strings before calling join().

main.py
list_of_numbers = [55, 10, 44] result = ' '.join(str(item) for item in list_of_numbers) print(result) # 👉️ 55 10 44

The string the join() method is called on is used as the separator between the
elements.

main.py
list_of_numbers = [55, 10, 44] result = ', '.join(str(item) for item in list_of_numbers) print(result) # 👉️ 55, 10, 44

You can also use the map() function to convert all items in the list to
strings before calling join().

main.py
list_of_numbers = [55, 10, 44] result = ' '.join(map(str, list_of_numbers)) print(result) # 👉️ 55 10 44

map()函数将一个函数和一个可迭代对象作为参数,并使用可迭代对象的每个项目调用该函数。