python删除连续相同字符
作者:野牛程序员:2023-08-11 10:29:33python阅读 3046
可以使用循环或正则表达式来删除字符串中的连续相同字符。以下是两种方法的示例:
使用循环: 使用循环遍历字符串,检查相邻字符是否相同,然后删除重复字符。
def remove_consecutive_duplicates(input_string): result = [input_string[0]] for char in input_string[1:]: if char != result[-1]: result.append(char) return ''.join(result) my_string = "aaabbbcccdddeee" new_string = remove_consecutive_duplicates(my_string) print(new_string) # 输出: "abcde"
使用正则表达式: 使用正则表达式来查找并替换连续相同字符。
import re def remove_consecutive_duplicates(input_string): return re.sub(r'(.)\\1+', r'\\1', input_string) my_string = "aaabbbcccdddeee" new_string = remove_consecutive_duplicates(my_string) print(new_string) # 输出: "abcde"
在第二种方法中,正则表达式 (.)\\1+ 匹配连续相同的字符,然后使用 \\1 来替换它们为单个字符。
无论哪种方法,都可以帮助删除字符串中的连续相同字符。可以根据实际需求选择适合的方法。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:python日期相减计算天数
- 下一篇:python字符串操作,删除、替换、拼接
