Write a function named first_non_repeating_letter that takes a string input, and >returns the first character that is not repeated anywhere in the string.
For example, if given the input 'stress', the function should return 't', since the >letter t only occurs once in the string, and occurs first in the string.
As an added challenge, upper- and lowercase letters are considered the same character, >but the function should return the correct case for the initial letter. For example, >the input 'sTreSS' should return 'T'.
If a string contains all repeating characters, it should return an empty string ("") or >None -- see sample tests.
題目理解:設計一函數,代入字串string後,返還第一個不重複出現於字串中的字元。另外英文大寫被視為相同字元,但返還時須返還首字母的正確大小寫形式。
def first_non_repeating_letter(string:str):
"""返還第一個於string中不重複的字元"""
#因不計大小寫差異,故先將string皆轉換為小寫形式
str_lower = string.lower()
for i in range(len(str_lower)):
#依序檢查字串中各個字元的數量,若發現數量為1的字元即返還
if str_lower.count(str_lower[i]) == 1:
#注意返還時索引需使用在原字串string上,來取得原本的字元的大小寫形式
return string[i]
return ""