Python中的print()函数是一个非常灵活和实用的工具,可以通过多种方式进行格式化和定制。以下是一些进阶技巧:
格式化字符串:使用str.format()或f-string(Python 3.6+)来格式化输出。
name = "Alice"age = 30# 使用str.format()print("My name is {} and I am {} years old.".format(name, age))# 使用f-stringprint(f"My name is {name} and I am {age} years old.")指定输出宽度:使用width参数指定输出的最小宽度,如果不足则在左侧填充空格。
print("Hello", end="", flush=True)print("World!")指定输出精度:使用precision参数指定浮点数的小数点后保留的位数。
pi = 3.141592653589793print("{:.2f}".format(pi)) # 输出:3.14文本对齐:使用<、>、^分别表示左对齐、右对齐、居中对齐。
print("{:<10}".format("left")) # 输出:left print("{:>10}".format("right")) # 输出: rightprint("{:=^10}".format("center")) # 输出: center 转义字符:使用\来转义特殊字符,例如换行符\n、制表符\t等。
print("Hello\nWorld!") # 输出: # Hello # World!分隔符和结束符:使用sep和end参数自定义分隔符和结束符。
print(1, 2, 3, sep="-", end="!\n") # 输出:1-2-3!输出到文件:将print()的输出重定向到文件。
with open("output.txt", "w") as f: print("Hello, world!", file=f)使用颜色:在终端中输出带有颜色的文本。
import sysprint("\033[31mRed text\033[0m", file=sys.stderr)这些只是print()函数的一些进阶技巧,更多高级功能可以通过学习其他Python库(如rich)来实现。




