【问题描述】 编写一个程序,当在一个字符串中出现指定子串时就删除它。 【输入形式】 用户在第一行输入一个字符串,用户在第二行输入一个子串。 【输出形式】 程序在下一行输出删除其中所有子串后的字符串。如果字符串不包含子串则输出原字符串本身。 【样例输入】 I am a boy! a 【样例输出】 I m boy! 【样例说明】用户首先输入字符串I am a boy!,然后输出子串a,程序会寻找字符串中的子串删除它,最后 将删除后的结果输出:I#m##boy! #表示空格。
时间: 2024-03-17 11:43:12 浏览: 18
这是一个字符串处理的问题,可以使用 Python 编写程序来解决。
以下是 Python 代码实现:
```python
s = input() # 输入字符串
sub = input() # 输入子串
new_s = s.replace(sub, '') # 删除子串
print(new_s)
```
具体解释:
1. 首先使用 `input()` 函数获取用户输入的字符串和子串。
2. 使用字符串的 `replace()` 方法将子串替换为空字符串,从而实现删除子串的功能。
3. 最后使用 `print()` 函数输出处理后的字符串。
注意:这个程序只删除了一个子串,如果字符串中有多个相同的子串,需要多次调用 `replace()` 方法进行删除。
相关问题
编写一个程序,当在一个字符串中出现指定子串时就删除它。
好的,我可以为您提供一个 Python 代码示例,用于删除字符串中的指定子串:
```python
def remove_substring(string, substring):
"""删除字符串中的指定子串"""
# 判断字符串是否包含子串
if substring not in string:
return string
# 使用 replace() 方法删除子串
new_string = string.replace(substring, "")
return new_string
```
使用示例:
```python
string = "Hello, World!"
substring = "l"
new_string = remove_substring(string, substring)
print(new_string) # 输出 "Heo, Word!"
```
这个程序会删除字符串中的所有指定子串,如果您只需要删除第一个出现的子串,可以使用 `replace()` 方法的第三个参数来指定替换次数。
编写一个程序,当在一个字符串中出现子串时就删除它。
以下是一个使用Python编写的程序,可以实现在一个字符串中删除指定子串的功能:
```python
def delete_substring(string, substring):
while substring in string:
index = string.find(substring)
string = string[:index] + string[index+len(substring):]
return string
```
程序中的 `delete_substring` 函数接收两个参数:`string` 表示原始字符串,`substring` 表示要删除的子串。程序使用一个循环,不断地查找并删除子串,直到原始字符串中不再出现该子串。具体来说,程序使用字符串的 `find` 方法查找子串在原始字符串中的位置,并使用字符串切片操作将子串从原始字符串中删除。
例如,如果我们要删除字符串 `"hello world"` 中的子串 `"o"`,可以这样调用函数:
```python
result = delete_substring("hello world", "o")
print(result) # 输出 "hell wrld"
```
注意,这个程序只能删除字符串中的一个子串。如果要删除多个子串,需要多次调用该函数。