Python print()

在本教程中,我们将了解更多关于Python打印函数的信息. 在我们最后的教程中,我们了解了 Python float函数。

Python 打印

Almost all of our previous tutorial contains the Python print() function. But we did not discussed about python print function to the fullest. Now we will learn it. At first we should know about the basic structure of python print function. That is given below; Python Print Format If you read our tutorial on Python Functions and arguments, then you should probably had the idea about the above function. The values receives a list of undefined variables. So, all the comma separated values will goes under the list values. So if you add more elements separated by comma, you will get a output where all the values are put together separated by space. The following example will guide you about the simple python print function usage.

 1# initialize 1st variable
 2var1 = 1
 3
 4# initialize 2nd variable
 5var2 = 'string-2'
 6
 7# initialize 3rd variable
 8var3 = float(23.42)
 9
10print(var1, var2, var3)

以下代码的输出将是。

11 string-2 23.42

因此,无论您想要打印多少个项目,只要把它们放在一起作为论点。

在 Python Print 中使用 sep 关键字

如果你看到上一节的示例,你会注意到这些变量是用一个空间分开的,但你可以将其定制为自己的风格,假设在上一节的代码中,你想使用 underscore(_)来分离这些值,然后你应该通过 underscore 作为 sep 关键字的值。

 1# initiaze 1st variable
 2var1 = 1
 3
 4# initialize 2nd variable
 5var2 = 'string-2'
 6
 7# initialize 3rd variable
 8var3 = float(23.42)
 9
10print(var1, var2, var3, sep='_')

你会得到你想要的结果这样。

11_string-2_23.42

Python 打印结尾关键字

打印函数的 end 键将设置在打印完成时需要附加的字符串。默认情况下, end 键被设置为 newline 字符。 因此,在完成打印后,所有变量都附加了 newline 字符。

 1# initialize a list
 2initList = ['camel', 'case', 'stop']
 3
 4# print each words using loop
 5print('Printing using default print function')
 6for item in initList:
 7    print(item)  # default print function. newline is appended after each item.
 8
 9print()  # another newline
10
11# print each words using modified print function
12print('Printing using modified print function')
13for item in initList:
14    print(item, end='-')

您将获得如下类似的输出

1Printing using default print function
2camel
3case
4stop
5
6Printing using modified print function
7camel-case-stop-

Python 打印到文件

在本节中,我们将了解有关‘file’的关键字。 实际上,文件的关键字用于将输出输出到特定文件中。 如果您阅读了我们之前的教程 Python 文件操作,那么您应该了解基本的文件操作。 因此,您必须先在可编写模式下打开文件,然后在 **print() 函数中使用文件指针作为文件关键字的值。 请参阅下面的代码来了解 python 打印文件的使用。

 1# open a file in writable mood
 2fi = open('output.txt', 'w')
 3
 4# initialize a list
 5initList = ['camel', 'case', 'stop']
 6
 7# print each words using loop
 8print('Printing using default print function')
 9for item in initList:
10    print(item, file=fi)  # use file keyword
11
12print(file=fi)
13
14# print each words using modified print function
15print('Printing using modified print function')
16for item in initList:
17    print(item, end='-', file=fi)  # use file keyword
18
19# close the file
20fi.close()

你会得到与前一个例子在输出文本文件中相同的输出. 这是关于Python打印的。 希望你能很好地理解它。 对于任何进一步的查询,请自由使用评论部分。

Published At
Categories with 技术
Tagged with
comments powered by Disqus