
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Remove all duplicates from a given string in Python
To remove all duplicates from a string in python, we need to first split the string by spaces so that we have each word in an array. Then there are multiple ways to remove duplicates.
We can remove duplicates by first converting all words to lowercase, then sorting them and finally picking only the unique ones. For example,
Example
sent = "Hi my name is John Doe John Doe is my name" # Seperate out each word words = sent.split(" ") # Convert all words to lowercase words = map(lambda x:x.lower(), words) # Sort the words in order words.sort() unique = [] total_words = len(words) i = 0 while i < (total_words - 1): while i < total_words and words[i] == words[i + 1]: i += 1 unique.append(words[i]) i += 1 print(unique)
Output
This will give the output −
['doe', 'hi', 'john', 'is', 'my']
- Related Articles
- Remove all duplicates from a given string in C#
- Python program to remove all duplicates word from a given sentence.
- Remove All Adjacent Duplicates In String in Python
- C# program to remove all duplicates words from a given sentence
- Java program to remove all duplicates words from a given sentence
- Remove All Adjacent Duplicates in String II in C++
- Remove Duplicates from Sorted Array in Python
- Python - Ways to remove duplicates from list
- How do you remove duplicates from a list in Python?
- Python program to remove Duplicates elements from a List?
- Print all distinct permutations of a given string with duplicates in C++
- Program to remove duplicate characters from a given string in Python
- Java program to remove all the white spaces from a given string
- Remove duplicates from a List in C#
- Remove Consecutive Duplicates in Python

Advertisements