在字符串中找出第一个只出现一次的字符,Python实现
时间: 2023-10-30 22:12:18 浏览: 48
可以使用Python内置的`collections`模块中的`Counter`来统计每个字符出现的次数,然后遍历字符串找到第一个出现次数为1的字符。
代码如下:
```python
from collections import Counter
def first_unique_char(s):
# 统计每个字符出现的次数
counter = Counter(s)
# 遍历字符串,找到第一个出现次数为1的字符
for c in s:
if counter[c] == 1:
return c
# 没有找到符合条件的字符
return None
```
示例:
```python
s = "abaccdeff"
print(first_unique_char(s)) # 输出 'b'
```
相关问题
python里在字符串中找出第一个只出现一次的字符
可以使用 collections.Counter 和字符串的 find 方法来实现。代码如下:
```python
import collections
def first_unique_char(s: str) -> int:
freq = collections.Counter(s)
for i, c in enumerate(s):
if freq[c] == 1:
return i
return -1
```
函数 first_unique_char 接收一个字符串 s 作为参数,返回该字符串中第一个只出现一次的字符的索引。如果不存在这样的字符,则返回 -1。
具体实现时,首先使用 Counter 函数统计字符串中每个字符出现的次数,然后遍历字符串,找到第一个出现次数为 1 的字符即可。
编写一个python程序,能在字符串中找出第一个只出现一次的字符
可以使用Python内置的Counter模块来实现这个功能,以下是示例代码:
```python
from collections import Counter
def first_unique_char(s):
count = Counter(s)
for c in s:
if count[c] == 1:
return c
return None
s = "abaccdeff"
print(first_unique_char(s)) # 输出 'b'
```
这个程序会在字符串中找出第一个只出现一次的字符,并返回它。如果字符串中没有只出现一次的字符,则返回None。