您正在迭代字符串并检查字符串本身中的字母,所以if condition is always True在这种情况下是您的。您需要的是在迭代字符串时维护一个单独的列表,其中包含您已经看到的所有字母。像这样,uniq_list = []a = 'abhishek'count = 0for x in a: if x not in uniq_list: # check if the letter is already seen. count += 1 # increase the counter only when the letter is not seen. uniq_list.append(x) # add the letter in the list to mark it as seen.print(count)
a = 'abhishek'count = 0uls = set()nls = set()for x in a: if x not in uls: uls.add(x) else: nls.add(x)print(len(uls - nls))它会打印字符,它只出现一次。输出:6