Python 仅删除alpha副本
在Python中,我希望删除字符串中的重复字母,而不是数字或空格。我想到了:Python 仅删除alpha副本,python,python-2.7,duplicate-removal,alphanumeric,Python,Python 2.7,Duplicate Removal,Alphanumeric,在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
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
语句等,但我无法让任何东西正常工作。尝试以下方法:
result = ""
for char in string:
if not (char.isalpha() and char in result):
result += char
试试这个:
result = ""
for char in string:
if not (char.isalpha() and char in result):
result += char
使用
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.
使用
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.
看来你就快到了。您只需在循环中添加一些检查:
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)
看来你就快到了。您只需在循环中添加一些检查:
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)
object()
此处仅用于确保要保留的字符的键始终是唯一的,因为每次object()
都会创建不同的对象。其他字符本身用作键,因此会过滤重复的字符
object()
此处仅用于确保要保留的字符的键始终是唯一的,因为每次object()
都会创建不同的对象。其他字符本身用作键,因此会过滤重复的字符。+1这是一个很好的解决方案,但这会产生一个额外的空间,因为周围的已被完全删除removed@NiklasHansson请参阅OP的更新:应保留多个数字。我的坏,他改变了他的例子。+1是一个很好的解决方案,但这会产生额外的空间,因为周围的
已完全覆盖removed@NiklasHansson参见OP的更新:应该保留多个数字。我的错,他改变了他的示例。+1是一个很好的简单解决方案,只希望字符串不会变得太大,或者二次运行时将在+1中启动,以获得一个简单的解决方案,只希望字符串不会变得太大,或者二次运行时将在这方面启动,就像一个bajillion一样。看起来很。。。令人敬畏的是,这应该得到无数的选票。看起来很。。。令人惊叹的