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的字符

学好python自动化,工作效率顶呱呱
原文地址:https://www.cnblogs.com/fenglovellx/p/8576048.html