在Python中,我想从字符串中删除重复的字母,但不删除数字或空格。我提出了:
result = []
seen = set()
for char in string:
if char not in seen:
seen.add(char)
result.append(char)
return "".join(result)
但这样做:
>>> delete_duplicate_letters("13 men were wounded in an explosion yesterday around 3:00pm.")
13 menwroudiaxplsyt:0.
我想要的时候:
>>> delete_duplicate_letters("13 men were wounded in an explosion yesterday around 3:00pm.")
13 men wr oud i a xpls yt 3:00.
我尝试使用letter
代替char
,isalpha()
函数和if int
语句等,但我无法使用任何内容。
答案 0 :(得分:2)
>>> from string import digits, whitespace
>>> from collections import OrderedDict
>>> s = set(whitespace + digits)
>>> ''.join(OrderedDict((object() if c in s else c, c) for c in text).values())
'12 men wr oud i a xpls yt 3:00.'
object()
此处仅用于确保您要留下的字符的键始终是唯一的,因为object()
每次都会创建一个不同的对象。其他字符用作键本身,因此重复过滤。
答案 1 :(得分:1)
试试这个:
result = ""
for char in string:
if not (char.isalpha() and char in result):
result += char
答案 2 :(得分:1)
使用str.isspace
和str.isdigit
:
strs = "13 men were wounded in an explosion yesterday around 3:00pm."
result = []
seen = set()
for char in strs:
if char not in seen:
if not (char.isspace() or char.isdigit()):
seen.add(char)
result.append(char)
print "".join(result)
<强>输出:强>
13 men wr oud i a xpls yt 3:00.
答案 3 :(得分:0)
result = []
seen = set()
for char in string:
if char.isdigit() or char.isspace():
result.append(char)
elif char not in seen:
seen.add(char)
result.append(char)
return "".join(result)