找出不重复字元
这篇文章会介绍使用 Python 的 for 循环、串列操作、字串操作和 if 判断式,实作找出不重复字元的方法。
本篇使用的 Python 版本为 3.7.12,所有范例可使用 Google Colab 实作,不用安装任何软件 ( 参考:使用 Google Colab )
基本原理
判断字元是否重复的方法,就是判断每个字元在字串中出现的次数,如果出现的次数大于 1 表示有重复,就用 repeat 串列纪录,如果出现次数等于 1 表示没有重复,就用 not_repeat 串列记录,如此一来就能够筛选出重复与不重复的字元。
编辑程序
按照原理,开始编辑程序:
text = input('請輸入一串英文或數字:') # 新增 text 變數,記錄輸入的字串
repeat = [] # 新增 repeat 變數為空串列
not_repeat = [] # 新增 not_repeat 變數為空串列
for i in text: # 使用 for 迴圈,依序取出每個字元
a = text.count(i, 0, len(text)) # 判斷字元在字串中出現的次數
if a>1 and i not in repeat: # 如果次數大於 1,且沒有存在 repeat 串列中
repeat.append(i) # 將字元加入 repeat 串列
if a == 1and i not in not_repeat: # 如果次數等於 1,且沒有存在 not_repeat 串列中
not_repeat.append(i) # 將字元加入 not_repeat 串列
print(repeat)
print(not_repeat)
微信扫码关注
抖音扫码关注