Discuss / Python / 打卡

打卡

Topic source

print(n,'\n',f,'\n',s1,'\n',s2,'\n',s3,'\n',s4) #用转义符换行

转义符和变量中间的那个逗号为什么不能省略呢?

这个写法是将转义符也当成了一个元素。每个元素用‘,’隔开了。这里‘,’的功能是输出一个空格,所以你打印出来每个换行后面都会有一个‘,’空格。

可以试试这样print(n,f,s1,s2,s3,s4,sep='\n')

你可以看下help(print),这个函数有五个默认参数,value,...,这个是收集参数,每个参数用‘,’隔开。sep=''则是默认的那个‘,’的功能是输出一个空格,所以我们只需要把这个默认‘,’的功能改成换行sep='\n'就可以了实现。

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

    Prints the values to a stream, or to sys.stdout by default.

    Optional keyword arguments:

    file:  a file-like object (stream); defaults to the current sys.stdout.

    sep:   string inserted between values, default a space.

    end:   string appended after the last value, default a newline.

    flush: whether to forcibly flush the stream.


  • 1

Reply