简体   繁体   English

为什么“ seq”不能循环工作?

[英]Why 'seq' not work in a loop?

for i in range(10):
    print(i, sep = ',', end = '')

It should be 0,1,2,3,4,5,6,7,8,9 ,but the truth is 应该是0,1,2,3,4,5,6,7,8,9 ,但事实是 在此处输入图片说明 The sep does not work. sep不起作用。 Thanks! 谢谢!

The optional sep argument is used to define the separator between comma separated argument values that are fed to the objects parameter of print . 可选的sep参数用于定义以逗号分隔的参数值之间的分隔符,这些参数值馈给printobjects参数。 objects is a variable argument parameter, which means it can take any number of arguments (or an unpacked iterable). objects是可变参数参数,这意味着它可以接受任意数量的参数(或解压缩的可迭代对象)。

From the docs : 文档

print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False) print(* objects,sep ='',end ='\\ n',file = sys.stdout,flush = False)

Print objects to the text stream file, separated by sep and followed by end. 将对象打印到文本流文件中,以sep分隔,然后以end分隔。 sep, end and file, if present, must be given as keyword arguments. sep,end和file(如果存在)必须作为关键字参数给出。

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. 所有非关键字参数都将像str()一样转换为字符串,并写入流中,以sep分隔,然后以end分隔。 Both sep and end must be strings; sep和end都必须是字符串; they can also be None, which means to use the default values. 它们也可以是None,这意味着要使用默认值。 If no objects are given, print() will just write end. 如果没有给出对象,print()只会写完。

A better way of writing your code would be the following: 编写代码的更好方法是:

print(*range(10), sep=',', end='')

This uses the * operator to unpack the iterable and feed each of its elements in as arguments to the print function. 这使用*运算符解压缩可迭代对象,并将其每个元素作为print函数的参数输入。

It is equivalent to: 它等效于:

print(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, sep=',', end='')

In this loop, i is always a one digit integer and this can't be seperated. 在此循环中, i始终是一位整数,并且不能将其分开。

It would be like this: 就像这样:

print("1", sep=',', end='')
print("2", sep=',', end='')
print("3", sep=',', end='')
...

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

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