What are the methods to remove duplicates and sort strings in Python?
There are several methods in Python for removing duplicates and sorting strings.
- Use the set() function to remove duplicates: convert the string into a set, which automatically removes duplicates. Then convert the set back into a string. Sample code is as follows:
s = "hello world"
s = ''.join(set(s))
print(s)
- Sort with the sorted() function: Convert the string to a list, then use the sorted() function to sort the list, and finally convert the sorted list back to a string. Example code is shown below:
s = "hello world"
s = ''.join(sorted(s))
print(s)
- Remove duplicates using the uniqueness of dictionary keys: Iterate through each character of the string, using each character as a key in the dictionary with arbitrary values, since we only care about the uniqueness of the keys. Finally, convert the dictionary keys back to a string. Example code is shown below:
s = "hello world"
s = ''.join(dict.fromkeys(s))
print(s)
- Sort using the sorting function of sets: Convert the string to a list, then use the sorted() function to sort the list, and finally convert the sorted list back to a string. Example code is as follows:
s = "hello world"
s = ''.join(sorted(set(s)))
print(s)
Here are some common methods in Python for removing duplicate strings and sorting them. Choose the appropriate method based on your specific needs to solve the problem.