Python3 输入和输出

程序与人交互离不开输入输出:input() 从键盘读入数据,print() 把结果打到屏幕。别看 它们简单,格式化、对齐、重定向等细节掌握好,输出的程序信息才会清晰易读。

input() 读入字符串

input() 会暂停程序等待键盘输入,按回车后把内容作为字符串返回:

name = input("请输入你的名字:")   # 运行后输入 Alice 回车
print("你好,", name)              # 输出:你好, Alice

注意:input() 返回的永远是字符串,需要数字时要手动转换:

age = int(input("请输入年龄:"))   # 输入 18
print(age + 1)                     # 输出:19

print() 的常用参数

print("a", "b", "c")          # 默认以空格分隔
print("a", "b", sep="-")      # 指定分隔符,输出:a-b
print("hello", end="")        # 默认结尾换行,end 可换成其他字符
print(" world")               # 输出:hello world

把内容写到文件,只需指定 file 参数:

with open("log.txt", "w") as f:
    print("这是一条日志", file=f)   # 输出进文件而不是屏幕

字符串格式化

name, score = "小明", 92.5
print("%s 考了 %.1f 分" % (name, score))      # % 占位符
print("{} 考了 {:.1f} 分".format(name, score))  # format 方法
print(f"{name} 考了 {score:.1f} 分")           # f-string,推荐
# 三行输出相同:小明 考了 92.5 分

对齐与补零示例

print(f"{'左':<8}|")     # 左对齐,宽度 8,输出:左       |
print(f"{'右':>8}|")     # 右对齐,输出:       右|
print(f"{'中':^8}|")     # 居中,输出:   中    |
print(f"{42:05d}")       # 数字补零,输出:00042

repr() 与 str() 的区别

str() 生成给人看的友好文本,repr() 生成给解释器/调试用的精确表示(常带引号):

s = "你好\n"
print(str(s))     # 输出:你好(换行被真正打印出来)
print(repr(s))    # 输出:'你好\n'(转义符按原文显示)

小结:input() 读入的字符串记得转类型;print() 用 sep/end/file 控制输出细节, f-string 做格式化最直观,调试时可用 repr() 看清数据的"真面目"。

笔记加载中…