如何编写Python代码打印任意变量的值?以及优雅打印各类变量(含内部元素)的实用方法有哪些?
嘿,这两个问题我熟得很!咱们一步步来解决~
1. 基础打印任意变量值的Python代码
其实Python自带的print()函数就能搞定基础的变量打印需求,不管是啥类型的变量,直接丢进去就能输出它的值。不过针对不同类型,效果略有不同,举几个常见例子:
- 标量对象(比如整数、字符串、布尔值):
num = 42 text = "Hello World" is_true = True print(num) # 输出: 42 print(text) # 输出: Hello World print(is_true) # 输出: True
- 列表、元组、字典这类容器:
my_list = [1, "apple", 3.14] my_tuple = (2, "banana", False) my_dict = {"name": "Alice", "age": 25, "hobbies": ["reading", "hiking"]} print(my_list) # 输出: [1, 'apple', 3.14] print(my_tuple) # 输出: (2, 'banana', False) print(my_dict) # 输出: {'name': 'Alice', 'age': 25, 'hobbies': ['reading', 'hiking']}
如果是你自己定义的类对象,默认print()会输出对象的内存地址,这时候你可以给类加上__str__方法,让它打印出你想要的内容:
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person(name={self.name}, age={self.age})" p = Person("Bob", 30) print(p) # 输出: Person(name=Bob, age=30)
2. 优雅打印(Pretty Print)任意变量的有效方法
如果变量结构比较复杂(比如嵌套多层的列表、字典),普通print()的输出会挤在一起,看着头疼。这时候Python标准库的pprint模块就派上用场了,它会自动格式化输出,让结构一目了然。
先导入模块:import pprint,然后用pprint.pprint()来替代print()就行,咱们针对你提到的所有类型逐个举例:
2.1 标量对象
对于标量,pprint和普通print差别不大,但胜在风格统一:
import pprint pprint.pprint(42) # 输出: 42 pprint.pprint("Hi there")# 输出: 'Hi there' pprint.pprint(None) # 输出: None
2.2 列表(包含标量或对象)
不管是单层还是嵌套列表,pprint都会自动换行、缩进,让层级清晰:
nested_list = [1, ["apple", "banana"], 3.14, [True, [False, None]]] pprint.pprint(nested_list)
输出效果:
[1, ['apple', 'banana'], 3.14, [True, [False, None]]]
如果是包含自定义对象的列表,只要对象有__repr__方法(比__str__更偏向于开发者视角的字符串表示),pprint也能友好显示:
class Book: def __init__(self, title, author): self.title = title self.author = author def __repr__(self): return f"Book(title='{self.title}', author='{self.author}')" book_list = [Book("1984", "George Orwell"), Book("To Kill a Mockingbird", "Harper Lee")] pprint.pprint(book_list)
输出:
[Book(title='1984', author='George Orwell'), Book(title='To Kill a Mockingbird', author='Harper Lee')]
2.3 字典(包含标量或对象)
字典是pprint最能发挥优势的场景之一,尤其是嵌套字典:
complex_dict = { "user": { "name": "Charlie", "age": 35, "contacts": { "email": "charlie@example.com", "phone": "123-456-7890" } }, "preferences": ["dark_mode", "notifications"] } pprint.pprint(complex_dict, indent=2) # 可以用indent参数调整缩进量
输出:
{ 'user': { 'age': 35, 'contacts': { 'email': 'charlie@example.com', 'phone': '123-456-7890' }, 'name': 'Charlie' }, 'preferences': ['dark_mode', 'notifications']}
2.4 元组
元组的处理和列表类似,pprint会帮你格式化多层嵌套的元组:
nested_tuple = (1, ("a", "b"), (3.14, (True, False))) pprint.pprint(nested_tuple)
输出:
(1, ('a', 'b'), (3.14, (True, False)))
额外技巧:调整pprint的输出风格
你还可以通过参数自定义输出:
width:设置每行的最大宽度,超过就换行depth:限制打印的嵌套层级(适合超级复杂的对象)compact:当内容能放下时,尽量放在一行
比如:
pprint.pprint(nested_list, width=20) # 强制更早换行
内容的提问来源于stack exchange,提问作者ssppjj
相关产品推荐
相关产品推荐

