Python代码的输出通常是通过`print()`函数实现的,它可以接受不同数据类型并完成格式化输出。以下是`print()`函数的基本用法和一些高级用法:
基本用法
print("Hello, World!") 输出字符串
格式化输出
使用占位符
name = "Tom"print("My name is %s" % name) 使用 %s 占位符
使用 `.format()` 方法
print("字符串 {},年龄:{}".format(name, user_age)) 使用 {} 占位符
同时输出多个变量
user_name = "Charlie"user_age = 8print("读者名:", user_name, "年龄:", user_age) 默认以空格隔开
输出到文件
with open("output.txt", "w") as file:print("写入文件", file=file)
输出控制
`sep` 参数:设置分隔符,默认是空格。
`end` 参数:设置结束字符,默认是换行符 `\n`。
`file` 参数:输出到指定文件。
`flush` 参数:设置是否立即刷新输出缓冲区,默认是 `False`。
示例代码
name = "Alice"age = 30print("My name is %s and I am %d years old." % (name, age))print("Hello, World! My name is %s and I am %d years old." % (name, age))print("Hello, World! My name is {} and I am {} years old.".format(name, age))print("Hello, World! My name is {} and I am {} years old.".format(name, age), sep=", ", end="!\n")
以上示例展示了如何使用`print()`函数进行基本的输出以及格式化输出。根据需要,你可以调整参数来控制输出的格式和方式
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/112606.html