python替换关键字
时间: 2024-10-10 10:11:45 浏览: 25
在Python中,替换字符串中的关键字通常使用`str.replace()`函数或字符串格式化方法。以下是两种常见的方式:
1. 使用`replace()`函数:
```python
old_keyword = "old_value"
new_keyword = "new_value"
original_string = "This is an example with the old keyword."
replaced_string = original_string.replace(old_keyword, new_keyword)
print(replaced_string) # 输出: This is an example with the new keyword.
```
2. 使用字符串格式化方法 (f-string 或 `.format()`):
```python
old_keyword = "old_value"
new_keyword = "new_value"
original_string = f"This is an example with the {old_keyword}."
# 或者
# original_string = "This is an example with the {}.".format(old_keyword)
replaced_string = original_string.replace(old_keyword, new_keyword)
print(replaced_string) # 输出: This is an example with the new value.
```
阅读全文