在Python中输出文字和数字,可以使用以下几种方法:
字符串拼接
```python
text = "Hello"
number = 42
print(text + str(number)) 使用字符串拼接
```
格式化字符串
```python
text = "Hello"
number = 42
print("{} {}".format(text, number)) 使用格式化字符串
```
这两种方法都可以有效地将文字和数字组合在一起输出。推荐使用格式化字符串,因为它更加灵活和易读。
建议
在实际编程中,推荐使用格式化字符串(即使用`{}`占位符和`.format()`方法),因为这种方式不仅代码简洁,而且易于维护和扩展。例如:
```python
name = "Alice"
age = 20
print("My name is {} and I am {} years old.".format(name, age))
这种方式可以清晰地看到每个变量的位置,并且在需要插入多个变量时,代码更加整洁。