python常见print用法
时间: 2024-07-27 09:00:53 浏览: 63
在Python中,`print()`函数是最基本也最常用的输出语句,用于将指定的内容输出到控制台或终端窗口。以下是`print()`的一些常见用法:
1. **简单文本输出**:
```python
print("Hello, World!")
```
2. **输出变量值**:
```python
name = "Alice"
age = 25
print("Name:", name, ", Age:", age)
```
3. **格式化输出**:
- 使用字符串连接符`+`或占位符`%`:
```python
formatted = "My name is %s and I am %d years old." % (name, age)
print(formatted)
- 使用f-string(Python 3.6及以上版本):
```python
print(f"My name is {name} and I am {age} years old.")
```
4. **数组、列表和元组输出**:
```python
numbers = [1, 2, 3]
print(numbers)
```
5. **字典输出键值对**:
```python
person = {"name": "Bob", "age": 30}
print(person.items())
```
6. **打印异常信息**:
```python
try:
# some code that may raise an exception
except Exception as e:
print(f"An error occurred: {e}")
```
7. **换行或缩进**:
```python
print("First line")
print("Second line") # 自动换行
print("\n" + "Another line") # 显式换行
```
阅读全文