寻找字符串“I think hope is a good thing.”中字符串“hope”的下标,并将字符串中的“hope”替换成其他事物,将新字符串保存到变量result中并在屏幕上输出。
时间: 2024-05-02 22:18:31 浏览: 96
代码如下:
```python
text = "I think hope is a good thing."
index = text.index("hope") # 获取字符串 "hope" 的下标
result = text[:index] + "love" + text[index+4:] # 将字符串 "hope" 替换成 "love"
print(result) # 输出新字符串
```
输出结果为:
```
I think love is a good thing.
```
相关问题
寻找字符串"I think hope is a good thing."中字符串"hope"的下标,并将字符串中的hope替换成freedom,将新字符串保存到变量result中并在屏幕上输出。(使用replace方法)
好的,我理解了你的要求。下面是代码实现:
```
# 定义原始字符串
string = "I think hope is a good thing."
# 寻找字符串 hope 的下标
index = string.index("hope")
# 将字符串 hope 替换成 freedom
result = string.replace("hope", "freedom")
# 输出结果
print("原始字符串:", string)
print("新字符串:", result)
```
输出结果为:
```
原始字符串: I think hope is a good thing.
新字符串: I think freedom is a good thing.
```
如有其他问题,可以继续问我哦。
阅读全文