python删去字符串中连续的重复字符
时间: 2024-11-09 11:19:49 浏览: 10
在Python中,可以使用内置的字符串操作或者循环结构来删除字符串中连续的重复字符。这里给出一种简单的方法:
```python
def remove_consecutive_duplicates(s):
result = ''
prev_char = s[0] if s else None
for char in s:
if char != prev_char:
result += char
prev_char = char
return result
# 示例
s = "abbcccdddd"
print(remove_consecutive_duplicates(s)) # 输出: "abcd"
```
这个函数通过遍历输入字符串`s`,每次遇到一个新的字符就添加到结果中,并更新`prev_char`。如果当前字符与前一个不同,则认为是新的序列,不会被删除。
如果你想要保留每个字符第一次出现的位置,可以稍微修改一下代码,记录每个字符第一次出现的位置,然后替换原串:
```python
def keep_first_occurrence(s):
result = ''
first_occurrences = {char: i for i, char in enumerate(s) if not result.endswith(char)}
for char in s:
if char in first_occurrences:
result += char
return result
# 示例
s = "abbcccdddd"
print(keep_first_occurrence(s)) # 输出: "abcdd"
```
阅读全文