在 Python 中,print 是一个内置函数,用于输出内容到控制台。它是最常用的输出函数之一。
1. 基本用法
print("Hello, world!")
这会输出:
Hello, world!
2. 使用字符串变量
你可以将字符串存储在变量中,然后使用 print 输出:
message = "Hello, world!"
print(message)
输出结果:
Hello, world!
3. 使用格式化字符串(f-string)
你可以使用 f-string 来格式化输出:
name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")
输出结果:
Hello, Alice! You are 30 years old.
4. 使用 print 的其他参数
print 函数还可以接受一些参数,比如 sep(分隔符)、end(结束符)等:
sep:指定输出的分隔符,默认是空格。end:指定输出的结束符,默认是换行符\n。
print("Hello", "world", sep="|")
输出结果:
Hello|world
print("Hello", end="")
print("world")
输出结果:
Hello world
5. 使用 print 的其他方式
你也可以使用 sys.stdout.write() 来输出内容:
import sys
sys.stdout.write("Hello, world!\n")
输出结果:
Hello, world!
总结
| 用途 | 说明 |
|---|---|
| 输出文本 | print() 函数最常用 |
| 使用变量 | 可以将字符串存储在变量中 |
| 格式化输出 | 使用 f-string 或其他格式化方法 |
| 控制输出格式 | 使用 sep 和 end 参数 |
| 更灵活的输出 | 使用 sys.stdout.write() |
如果你有其他问题,欢迎继续提问!