print函数
使用`print()`函数可以输出文本、变量、计算结果等。
语法:`print(*objects, sep='', end='\n', file=sys.stdout, flush=False)`。
`objects`:可以一次输出多个对象,用逗号分隔。
`sep`:指定分隔符,默认为空格。
`end`:指定输出结束符,默认为换行符`\n`。
`file`:输出到指定文件或设备,默认为标准输出`sys.stdout`。
`flush`:是否立即刷新输出缓冲区,默认为`False`。
格式化输出
使用`str.format()`方法或f-string(Python 3.6+)进行格式化输出。
示例:
name = "xiaoming"
age = 28
print("My name is {}, {} years old!".format(name, age))
print(f"My name is {name}, {age} years old!")
文件输出
使用文件对象的`write()`方法将内容写入文件。
示例:
with open('output.txt', 'w') as file:
file.write('Hello, world!')
标准输出和重定向输出
可以将输出重定向到文件或其他设备。
示例:
print("Hello, world!", file=open('output.txt', 'w'))
以上是Python中常见的输出方法。您可以根据需要选择合适的方法进行输出