python在字符串中添加字符
时间: 2025-02-16 11:15:34 AIGC 浏览: 45
在Python中,你可以使用加号(+)操作符或者`format()`方法或者f-string(格式化字符串字面量)来向字符串中添加字符。以下是三种常见的方式:
1. 使用加号操作符:
```python
str1 = "Hello"
new_str = str1 + " World" # 新字符串会是 "Hello World"
```
2. 使用`format()`方法:
```python
str1 = "Hello"
char_to_add = " World"
new_str = "{} {}".format(str1, char_to_add) # 新字符串同样会是 "Hello World"
```
注意在Python 3.6之后,`format()`方法已经被f-string所替代:
3. 使用f-string(格式化字符串字面量):
```python
str1 = "Hello"
new_str = f"{str1} {char_to_add}" # 输出同上,"Hello World"
```
以上就是向Python字符串中添加字符的基本方法。如果你需要在字符串中插入变量的值,那么可以直接使用变量名。
阅读全文
相关推荐













