你好,学习者。在本教程中,我们将进一步了解Python打印函数。在上一个教程中,我们了解到Python浮子功能。
Python印花
我们以前的教程几乎都包含Pythonprint()
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函数和参数,那么你应该对上面的函数有个想法。
这个values
receives a list of undefined variables. So, all the comma separated values will goes under the list 价值观. 因此,如果您添加更多用逗号分隔的元素,您将得到一个输出,其中所有值以空格分隔放在一起。下面的示例将指导您如何使用简单的python打印函数。
# initialize 1st variable
var1 = 1
# initialize 2nd variable
var2 = "string-2"
# initialize 3rd variable
var3 = float(23.42)
print(var1, var2, var3)
以下代码的输出将是。
1 string-2 23.42
所以,你想打印多少条,就把它们放在一起作为参数。
在python打印函数中使用sep关键字
如果看到上一节的示例,您会注意到变量是用空格分隔的。但你可以根据自己的风格定制。
假设在前面的代码中,您希望使用下划线(u)分隔这些值。然后应该传递下划线作为九月关键字。下面的函数将演示使用python print sep关键字的想法。
# initiaze 1st variable
var1 = 1
# initialize 2nd variable
var2 = "string-2"
# initialize 3rd variable
var3 = float(23.42)
print(var1, var2, var3, sep="_")
这样你就能得到你想要的输出。
1_string-2_23.42
Python打印结束关键字
这个结束打印函数的键将设置打印完成时需要追加的字符串。
默认情况下结束键由换行符设置。因此,在打印完所有变量后,会附加一个换行符。因此,我们在不同的行中得到每个print语句的输出。但是现在我们将在print语句末尾用连字符(-)覆盖换行符。请参见以下示例。
# initialize a list
initList = ["camel", "case", "stop"]
# print each words using loop
print("Printing using default print function")
for item in initList:
print(item) # default print function. newline is appended after each item.
print() # another newline
# print each words using modified print function
print("Printing using modified print function")
for item in initList:
print(item, end="-")
你将得到如下输出
Printing using default print function
camel
case
stop
Printing using modified print function
camel-case-stop-
Python打印到文件
在本节中,我们将了解file
keyword. Actually file keyword is used for extracting output to a specified file. If you read our previous tutorial Python文件操作,那么您应该了解基本的文件操作。
因此,您必须先以可写模式打开一个文件,然后在中使用文件指针作为file关键字的值打印()功能。请参阅以下代码以了解python打印文件的用法。
# open a file in writable mood
fi = open("output.txt", "w")
# initialize a list
initList = ["camel", "case", "stop"]
# print each words using loop
print("Printing using default print function")
for item in initList:
print(item, file=fi) # use file keyword
print(file=fi)
# print each words using modified print function
print("Printing using modified print function")
for item in initList:
print(item, end="-", file=fi) # use file keyword
# close the file
fi.close()
您将在输出文本文件中获得与前一个示例相同的输出。
这就是Python打印的全部内容。希望你能理解。对于任何进一步的查询,可以使用comment部分。祝你好运。