python输出
以下是 Python 语言输出相关的知识点:
1. print()
函数基础用法
print()
是 Python 中用于输出信息的内置函数。基本语法是 print(value, ..., sep=' ', end='\n')
。
- 输出单个值:
python
print(123)
print("Hello, World!")
- 输出多个值:可以同时输出多个值,值之间用逗号分隔,默认用空格分隔各个值。
python
print(1, 2, 3)
print("apple", "banana", "cherry")
2. 自定义分隔符和结束符
sep
参数:用于指定多个值之间的分隔符,默认是空格。
python
print(1, 2, 3, sep=',')
end
参数:用于指定输出语句的结束字符,默认是换行符\n
。
python
print("Hello", end=' ')
print("World!")
3. 格式化输出
旧式字符串格式化(%
操作符)
- 可以使用
%
操作符来格式化字符串,常见的格式说明符有%s
(字符串)、%d
(整数)、%f
(浮点数)等。
python
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
新式字符串格式化(str.format()
方法)
- 使用
str.format()
方法可以更灵活地格式化字符串。
python
name = "Bob"
age = 30
print("My name is {} and I'm {} years old.".format(name, age))
f - 字符串(格式化字符串字面值)
- 从 Python 3.6 开始,支持 f - 字符串,它提供了一种更简洁的格式化字符串的方式。
python
name = "Charlie"
age = 35
print(f"My name is {name} and I'm {age} years old.")
4. 输出到文件
可以将 print()
函数的输出重定向到文件中。
python
with open('output.txt', 'w') as f:print("This is written to a file.", file=f)
5. 输出转义字符
在字符串中使用转义字符可以实现特殊的输出效果,例如换行符 \n
、制表符 \t
等。
python
print("Line 1\nLine 2")
print("Column 1\tColumn 2")
6. 输出对象的字符串表示
- 对于自定义类的对象,可以通过定义
__str__()
或__repr__()
方法来控制对象的输出格式。
python
class Person:def __init__(self, name, age):self.name = nameself.age = agedef __str__(self):return f"Person(name={self.name}, age={self.age})"p = Person("David", 40)
print(p)
以上就是 Python 语言输出方面的主要知识点,这些知识可以帮助你在不同场景下灵活地输出信息。
分享
分享一些关于Python语言的学习资源
用Python语言实现一个简单的猜数字游戏
介绍一下Python语言中的数据类型