Python:删除字符串中的字符
时间: 2024-02-28 16:56:00 浏览: 20
可以使用 Python 的字符串操作中的 replace() 方法来删除一个字符串中的字符。例如,删除字符串 "Hello World!" 中的字符 "o",可以使用如下代码:
```
string = "Hello World!"
new_string = string.replace("o", "")
print(new_string)
```
输出结果为:
```
Hell Wrld!
```
在上面的代码中,replace() 方法使用空字符串 "" 来替换掉所有的字符 "o"。这样就实现了删除字符串中的字符的功能。
相关问题
第1关:删除字符串中的指定字符
题目描述:给定一个字符串和一个字符,将字符串中所有的指定字符删除。
示例:
输入:str = "hello world", char = 'l'
输出:heo word
输入:str = "leetcode", char = 'e'
输出:lctod
解题思路:遍历字符串中的每个字符,如果当前字符不等于指定字符,则将该字符加入到结果字符串中。
参考代码:
```python
def delete_char(str, char):
res = ""
for c in str:
if c != char:
res += c
return res
```
测试一下:
```python
print(delete_char("hello world", 'l')) # heo word
print(delete_char("leetcode", 'e')) # lctod
```
python删除字符串中字符
要删除字符串中的字符,可以使用Python的字符串函数replace(),它可以将字符串中的所有指定字符替换为其他字符或删除字符。例如,下面的代码将从字符串中删除所有的字母e:
``` python
string = "Hello, world!"
new_string = string.replace("e", "")
print(new_string)
```
输出结果为:
```
Hllo, world!
```
另外,如果你想删除字符串中的所有空格,可以使用字符串函数replace()将空格替换为一个空字符串,如下所示:
``` python
string = " Hello, world! "
new_string = string.replace(" ", "")
print(new_string)
```
输出结果为:
```
Hello,world!
```