删除重复字符python
时间: 2023-11-08 08:03:51 浏览: 47
要删除字符串中的重复字符,你可以使用Python中的集合(set)来完成。集合是由唯一元素组成的无序集合,因此将字符串转换为集合,然后再将集合转换回字符串即可去除重复字符。
下面是一个示例代码:
```python
def remove_duplicates(string):
unique_chars = set(string)
result = ''.join(unique_chars)
return result
# 示例用法
string = "abccba"
result = remove_duplicates(string)
print(result) # 输出: "abc"
```
相关问题
python删除重复字符
你可以使用以下代码来删除字符串中的重复字符:
```python
def remove_duplicates(string):
# 将字符串转换为列表
string_list = list(string)
# 创建一个空集合
seen = set()
# 用一个循环遍历列表中的每个字符
# 如果这个字符不在集合中,就将其加入集合并添加到新列表中
# 否则,忽略它
new_list = []
for char in string_list:
if char not in seen:
seen.add(char)
new_list.append(char)
# 将新列表转换为字符串并返回
return ''.join(new_list)
```
你可以将要删除重复字符的字符串作为参数传递给上述函数。
python删除重复字符串
可以使用 set() 函数来删除重复的字符串,然后再将其转换回列表。以下是一个示例代码:
```python
my_list = ['apple', 'banana', 'orange', 'apple', 'banana']
my_list = list(set(my_list))
print(my_list)
```
输出结果为:
```
['banana', 'apple', 'orange']
```
这样就删除了列表中的重复字符串。