s = "aadarsh , aravind aadarsh,"
st=s.split()
lst=[]
for i in st:
if i not in lst:
lst.append(i)
print(' '.join(lst))
这是我的程序,但无法获得我想要的输出
我的示例字符串是s=";aadarsh,aravind aadarsh;并且我的输出应该是->阿拉文德·阿达尔什所有的重复都应该删除,包括逗号以及如何做到这一点。
问题似乎在于拆分有时应该使用逗号,有时应该使用空格。改为使用re.split
:
s = "aadarsh , aravind aadarsh,"
st=re.split("[s,]+", s)
lst=[]
for i in st:
if i and i not in lst:
lst.append(i)
print(' '.join(lst))
==> aadarsh aravind
一个更简单的解决方案是使用一个集合:
s = "aadarsh , aravind aadarsh,"
# (use comprehension to drop empty strings)
lst = [x for x in set(re.split("[s,]+", s)) if x]
print(' '.join(lst))