在Python中,`print()`函数用于将文本或变量的值输出到控制台。以下是`print()`函数的基本用法:
基本用法
打印字符串:
print("Hello, World!")
打印变量:
name = "John"
print("My name is", name)
指定分隔符:
print("apple", "banana", "orange", sep=", ", end=".\n")
格式化输出
使用`%`格式化:
age = {"赵敏": 25, "张无忌": 26}
print("赵敏 is %d years old, 张无忌 is %d years old" % age)
使用`format`方法:
print("赵敏 is {0[赵敏]} years old, 张无忌 is {0[张无忌]} years old".format(age))
其他用法
不换行:
a = 2
b = 4
print(a, b, end=", ")
使用ASCII码:
print(chr(33), chr(34), chr(35))
参数说明
`*objects`:要打印的对象,可以是多个,用逗号分隔。
`sep`:指定多个对象之间的分隔符,默认为空格。
`end`:指定打印结束后的字符,默认为换行符`\n`。
`file`:要写入的文件对象,默认为`sys.stdout`。
`flush`:布尔值,如果为`True`,则输出流会被强制刷新。
示例
print("Hello", "World", sep=", ", end="!\n") 输出:Hello, World!
print(1, 2, 3, sep=", ", end="!\n") 输出:1, 2, 3!
print(1 + 2 * 3 - 4 2, end="!\n") 输出:-1.0! (包含运算符号的表达式将结果输出)
以上是`print()`函数的基本用法和一些格式化输出的例子。您可以根据需要调整参数来控制输出的格式