Ilham Learning
Ilham Learning

Reputation: 57

Python replace and remove duplicate word in list

I'm trying to replace keyword and remove the duplicate words. But currently, I couldnt produce the result like I want. Here is my code :

words = 'AZ:ABC,AZ:DEF,AZ:GHI,AZ:ABC-OO'

words = words.replace('AZ:', '') 
words = words.replace(',', '\',\'')
words = words.replace('-OO', '')
words = '\'' + words + '\''

print(words )

totalBeforeCount = len(words)
print(totalBeforeCount)

filtering = list(set(words))
print(filtering)
print(len(filtering))

Below is my result I have currently :

enter image description here

So as you can see, instead it should remove one of ABC, it's actually separate them by alphabet. My expected result should be : 'ABC','DEF'GHI'.

Thanks a lot!

Upvotes: 0

Views: 113

Answers (2)

Parthi
Parthi

Reputation: 76

Instead of using replace we can first split with respect to ":" then split with respect to "," gives the expected result.

>> words.split(":")
>> ["'ABC','DEF','GHI','ABC'"]

>> words.split(":")[0].split(",")
>> ["'ABC'", "'DEF'", "'GHI'", "'ABC'"]

In one line

>> set(words.split(":")[0].split(","))
>> {"'ABC'", "'DEF'", "'GHI'"}

Upvotes: 0

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

instead of trying to format the string to look like it has quotes around the commas, just use .split(",") to get back an actual list:

words = 'AZ:ABC,AZ:DEF,AZ:GHI,AZ:ABC-OO'
words = words.replace('AZ:', '') 
words = words.replace('-OO', '')
list_of_words = words.split(",")
print(list_of_words)
print(set(list_of_words))

Upvotes: 4

Related Questions