unique characters in a string python code example
Example 1: count characters in string python
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
Example 2: find unique char in string python
In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']
Example 3: first unique character in a string python
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
frequency = {}
for i in s:
if i not in frequency:
frequency[i] = 1
else:
frequency[i] +=1
for i in range(len(s)):
if frequency[s[i]] == 1:
return i
return -1
ob1 = Solution()
print(ob1.firstUniqChar("people"))
print(ob1.firstUniqChar("abaabba"))