Python:从字符串中删除重复字符的最佳方法 [英] Python: Best Way to remove duplicate character from string

查看:248
本文介绍了Python:从字符串中删除重复字符的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Python 从字符串中删除重复字符?例如,假设我有一个字符串:

foo = "SSYYNNOOPPSSIISS"

如何制作字符串:

foo = 概要

我是 python 的新手,我累了,它正在工作.我知道有一个聪明和最好的方法来做到这一点..只有经验才能证明这一点..

def RemoveDupliChar(Word):新词 = " "指数 = 0对于 Word 中的字符:如果 char != NewWord[index]:新词 += 字符指数 += 1打印(NewWord.strip())

注意:顺序很重要,这个问题与 这个一个.

解决方案

使用 itertools.groupby:

<预><代码>>>>foo = "SSYYNNOOPPSSIISS">>>导入迭代工具>>>''.join(ch for ch, _ in itertools.groupby(foo))'概要'

How can I remove duplicate characters from a string using Python? For example, let's say I have a string:

foo = "SSYYNNOOPPSSIISS"

How can I make the string:

foo = SYNOPSIS

I'm new to python and What I have tired and it's working. I knew there is smart and best way to do this.. and only experience can show this..

def RemoveDupliChar(Word):
        NewWord = " "
        index = 0
        for char in Word:
                if char != NewWord[index]:
                        NewWord += char
                        index += 1
        print(NewWord.strip()) 

NOTE: Order is important and this question is not similar to this one.

解决方案

Using itertools.groupby:

>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'

这篇关于Python:从字符串中删除重复字符的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆