python删除字符串中重复的字符(只保留一个不重复字符)
时间: 2023-11-23 09:07:00 浏览: 96
可以使用集合(set)来去除重复字符,然后将集合转换为字符串即可。
代码如下:
```python
s = "hello world"
s = ''.join(set(s))
print(s)
```
输出结果为:
```
eohwrdl
```
注意,这种方法没有保留原字符串的顺序。如果需要保留顺序,可以使用有序集合(OrderedDict)来实现。
代码如下:
```python
from collections import OrderedDict
s = "hello world"
s = ''.join(OrderedDict.fromkeys(s))
print(s)
```
输出结果为:
```
helowrd
```
相关问题
使用python统计字符串中重复字符个数
可以使用字典来记录每个字符出现的次数,然后遍历字符串并更新字典。最后,将字典中值大于1的键值对统计即可。下面是示例代码:
```python
def count_duplicate_chars(s):
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
count = 0
for k, v in freq.items():
if v > 1:
count += 1
return count
```
使用示例:
```python
s = "hello world"
duplicate_count = count_duplicate_chars(s)
print(f"There are {duplicate_count} duplicate characters in '{s}'")
# 输出:There are 3 duplicate characters in 'hello world'
```
python删除字符串中连续的重复字符
可以使用正则表达式来实现删除字符串中连续的重复字符。
以下是一个示例代码:
```python
import re
def remove_duplicates(string):
# 使用正则表达式将连续重复的字符替换为单个字符
pattern = re.compile(r'(.)\1+')
return pattern.sub(r'\1', string)
# 示例用法
string = "aaabbbcccddd"
new_string = remove_duplicates(string)
print(new_string) # 输出: "abcd"
```
在上述代码中,`remove_duplicates` 函数使用正则表达式将连续重复的字符替换为单个字符,并返回新的字符串。其中,`pattern` 对象使用了正则表达式 `(.)\1+`,该表达式匹配任意一个字符后跟着一个或多个相同的字符,`\1` 表示第一个捕获组(即第一个括号内的内容,即匹配的重复字符),最终将重复的字符替换为单个字符。