python 字符串连接函数
时间: 2024-12-24 16:13:58 浏览: 3
Python 中字符串连接有几种方法:
1. **+ 操作符**:这是最基础的字符串连接方式,通过加号 (+) 连接两个或多个字符串。例如:
```python
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出:Hello World
```
2. **join() 方法**:适用于连接序列(如列表、元组或字符串切片)中的所有元素,比如:
```python
words = ["Hello", " ", "World"]
result = " ".join(words)
print(result) # 输出:Hello World
```
3. **f-string 或 format() 函数**:这两种方法用于插入变量到字符串中,适合动态构建字符串。例子如下:
```python
name = "Alice"
age = 25
result = f"My name is {name} and I am {age} years old."
print(result) # 输出:My name is Alice and I am 25 years old.
```
阅读全文