在 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() 打印以空格分隔的元素列表
要打印以空格分隔的元素列表:
- Use the
str.join()
method to join the list into a string with a space
separator. - If the list contains numbers, convert them to strings.
- Use the
print()
function to print the string.
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.
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()
.
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.
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()
.
list_of_numbers = [55, 10, 44] result = ' '.join(map(str, list_of_numbers)) print(result) # 👉️ 55 10 44
map()函数将一个函数和一个可迭代对象作为参数,并使用可迭代对象的每个项目调用该函数。