写在前面
一直以来我都是使用print()
来打印一些基本的信息,比如我们学习Python语言的第一个程序。
print('Hello, World!')
有时候我们还会指定分隔符输出。
print('apple', 'orange', 'banana', sep=', ')
输出:
apple, orange, banana
输出会使用sep
参数指定的分隔符。
输出彩色的内容
其实,官方文档中并没有提到这个用法。看起来确实特别有意思,并且,他不需要借助任何的外部库。
print('\x1b[31mhello')
这行代码中,\x1b[31m
是一个 ASCII 转义字符。在 'hello' 前面添加这个转义字符可以让 'hello' 以红色打印出来。
当我们打印转义字符时,会发生一些奇怪的事情,比如添加颜色,移动光标等等。在这种情况下,这个特定的转义字符可以让我们以红色打印文本。
打印蓝色文本:
print('\x1b[34mhello')
打印绿色文本:
print('\x1b[32mhello')
结果:
打印多色文本:
我们可以在一行中使用多个转义字符来打印多色文本。
print('\x1b[31mhello \x1b[32mnew \x1b[34mworld')
结果:
哈哈,是不是很有趣
但是这看起来有点繁琐,你可能不想记这些复杂的转义字符。所以我搜索了一下,找到了这个库:colorama
安装它:
pip install colorama
下面就可以愉快地使用了
from colorama import Fore
print(f'{Fore.RED}apple {Fore.GREEN}orange {Fore.BLUE}pear')
你看,我们不需要再记住那些奇怪的转义序列了。
print()的基础用法
Python 中的 print()
函数有很多有用的用法和功能,让我来为您一一介绍:
print('Hello, World!')
这会输出 Hello, World!
到控制台。
print('apple', 'orange', 'banana')
这会输出 apple orange banana
。默认情况下,参数之间用空格分隔。
print('apple', 'orange', 'banana', sep=', ')
这会输出 apple, orange, banana
。使用 sep
参数可以指定分隔符。
print('Hello', end='!')
print('World')
这会输出 Hello!World
。默认情况下,print()
会在输出后添加一个换行符,使用 end
参数可以指定其他字符。
name = 'Alice'
age = 25
print(f'My name is {name} and I'm {age} years old.')
这会输出 My name is Alice and I'm 25 years old。
使用 f-string 可以方便地插入变量。
with open('output.txt', 'w') as f:
print('This will be written to a file.', file=f)
这会将文本写入 output.txt
文件,而不是打印到控制台。
import sys
print('This is an error message.', file=sys.stderr)
这会将文本输出到错误流,而不是标准输出流。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person('Alice', 25)
print(person)
默认情况下,print()
会打印对象的字符串表示形式。您可以自定义对象的 __str__()
或 __repr__()
方法来控制输出。
这就是 Python 中 print()
函数的一些常用用法,希望对您有所帮助。如果您还有其他问题,欢迎随时询问。
写在最后
希望能帮助到你。