Python:返回字符串中第一个不重复的字母和位置

返回字符串中第一个不重复的字母和位置


# -*- coding: utf-8 -*-
def first_char(str):
    dict1 = {}
    for i in range(len(str)):
        #累计字符的出现次数
        if str[i] in dict1:
            dict1[str[i]] += 1
        #只出现一次,key对应的value就记1次
        else:
            dict1[str[i]] = 1
    for i in range(len(str)):
        if dict1[str[i]] == 1:
            return str[i], i+1
if __name__ == '__main__':
    str1 = input('please input string:')
    print(first_char(str1))

 

将字符串的字符作为key,出现次数作为value 保存为字典,再从字典中找到value=1的字符

posted @ 2018-03-15 20:22  凤凤1029  阅读(3952)  评论(0编辑  收藏  举报