-3
s = "aadarsh , aravind aadarsh,"
st=s.split()
lst=[]
for i in st:
    if i not in lst:
         lst.append(i)
print(' '.join(lst))

this is my program but am not able to get my desired output

My sample string is s = "aadarsh , aravind aadarsh," and my output should be -> aadarsh , aravind and all the duplicates should be removed including commas as well how to do it.

Dexter
  • 1
  • `print(s.split())` - it contains `'aadarsh'` and `'aadarsh,'` which are totally different from a computational point of view. Clean your data - you do nothing to strip a comma from anything before comparing. – Patrick Artner Aug 10 '20 at 06:40
  • @Dexter you didn't tell the split function where to make the break. If you do .split("a") you'll get "","d" ,"rsh" and so on. If you do not pass anything it 's assumed that you want to split at spaces. – Vishesh Mangla Aug 10 '20 at 06:43

1 Answers1

0

The issue seems to be with the fact that split should sometimes work with a comma, and sometimes with a space. Use re.split instead:

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

An even simpler solution would be to use a set:

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))
Roy2012
  • 11,755
  • 2
  • 22
  • 35