检查字符串“Life is short.l use python”中是否包含字符串“python”,若包含则替换为“python”后输出新字符串,否则输出原字符串
时间: 2024-01-01 11:04:10 浏览: 67
原始字符串为:
```python
s = "Life is short. I use python"
```
使用 `in` 操作符检查是否包含字符串 `"python"`:
```python
if "python" in s:
new_s = s.replace("python", "Java")
print(new_s)
else:
print(s)
```
输出:
```
Life is short. I use Java
```
相关问题
编写程序,检查字符串"Life is short.I use python"中是否包含字符串"python",若包含则替换为"Python"
是的,字符串"Life is short.I use python"包含字符串"python",可以使用Python代码将它替换为"Python"。以下是示例代码:
```python
string = "Life is short.I use python"
if "python" in string:
string = string.replace("python", "Python")
print(string)
```
输出结果是:"Life is short.I use Python"。
编写python程序,检查字符串" Life is short. I use python"中是否包含字符串"python",若包含则替换为"Python"后输出新字符串,否则输出原字符串。
可以使用Python中的字符串方法`find()`来检查字符串中是否包含另一个字符串,并返回其索引位置。如果返回-1,则表示未找到该字符串。根据这个方法,可以编写如下程序:
```python
string = "Life is short. I use python"
if string.find("python") != -1:
new_string = string.replace("python", "Python")
print(new_string)
else:
print(string)
```
输出结果为:
```
Life is short. I use Python
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)