python常见语法总结-打印函数

1.\n 换行

print(’‘) 打印函数

print('\n'.join(['\t'.join([f"{j} × {i} = {i * j}" for j in range(1, i + 1)]) for i in range(1, 10)]))

Python打印函数用法详解

1. 基本打印

python

复制

print("Hello, World!")

输出:

复制

Hello, World!

2. 打印多个变量(默认用空格分隔)

python

复制

name = "Alice"
age = 25
print("Name:", name, "Age:", age)

输出:

复制

Name: Alice Age: 25

3. 自定义分隔符(sep 参数)

python

复制

print("2023", "12", "31", sep="-")

输出:

复制

2023-12-31

4. 取消自动换行(end 参数)

python

复制

print("Loading", end="... ")
print("Done!")

输出:

复制

Loading... Done!

5. 打印到文件(file 参数)

python

复制

with open("output.txt", "w") as f:
    print("This will be written to a file", file=f)

(内容会写入 output.txt 文件)

6. 格式化输出(f-string 推荐方式)

python

复制

price = 19.99
print(f"The price is ${price:.2f}")

输出:

复制

The price is $19.99

7. 旧式格式化(兼容写法)

python

复制

print("My name is %s and I'm %d years old" % ("Bob", 30))

输出:

复制

My name is Bob and I'm 30 years old

8. 打印特殊字符

python

复制

print("First line\nSecond line\tIndented")

输出:

复制

First line
Second line    Indented

注意事项:

  • Python 3 的 print() 是一个函数,必须有括号

  • 打印对象时会自动调用其 __str__() 方法

  • 可以通过 print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) 调整参数

需要更复杂的输出时,可以结合字符串的 .format() 方法或第三方库(如 pprint 用于美化打印数据结构)。

你可能感兴趣的:(python,开发语言)