寻找字符串"I think hope is a good thing."中字符串"hope"的下标,并将字符串中的hope替换成freedom,将新字符串保存到变量result中并在屏幕上输出。(使用replace方法)
时间: 2024-03-09 18:49:37 浏览: 52
好的,代码如下:
```python
str1 = "I think hope is a good thing."
index = str1.index("hope")
result = str1.replace("hope", "freedom")
print("原始字符串:", str1)
print("字符串 'hope' 的下标:", index)
print("替换后的字符串:", result)
```
输出结果为:
```
原始字符串: I think hope is a good thing.
字符串 'hope' 的下标: 8
替换后的字符串: I think freedom is a good thing.
```
相关问题
.寻找字符串“I think hope is a good thing.”中字符串“hope”的下标,并将字符串中的“hope”替换成其他事物,将新字符串保存到变量 result 中并在屏幕上输出。
好的,以下是Python的实现代码:
```python
string = "I think hope is a good thing."
index = string.find('hope')
if index != -1:
result = string[:index] + 'love' + string[index+4:]
print(result)
else:
print("字符串中未找到'hope'")
```
输出结果为:`I think love is a good thing.`。
阅读全文