Python检查字符串中是否包含字符串“python”,若包含则替换为"PYTHON"后输出新字符串
时间: 2023-12-28 22:04:49 浏览: 31
可以使用Python中的 `in` 运算符来检查一个字符串中是否包含另一个字符串,然后使用 `replace()` 方法来替换字符串中的指定子串。以下是一个示例代码:
```python
string = "Hello, I love Python programming"
if "python" in string.lower():
new_string = string.replace("python", "PYTHON")
print("替换前的字符串:", string)
print("替换后的字符串:", new_string)
else:
print("字符串中不包含 'python' 子串")
```
输出结果为:
```
替换前的字符串: Hello, I love Python programming
替换后的字符串: Hello, I love PYTHON programming
```
这里我们使用了 `lower()` 方法将字符串转换为小写,然后使用 `in` 运算符检查是否包含子串 "python"。如果包含,则使用 `replace()` 方法将其替换为 "PYTHON"。否则,我们打印出字符串中不包含 "python" 子串的提示信息。
相关问题
检查字符串“Life is short.l use python”中是否包含字符串“python”,若包含则替换为“python”后输出新字符串,否则输出原字符串
原始字符串为:
```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
```
编写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)
![](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)
![](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)