python中內置函數(shù)ord()返回字符串的ASCII數(shù)值實例詳解
常用 ASCII 碼表對照表:
注意如下幾點:
0-9:48-57A-Z:65-90a-z:97-122
ord()函數(shù)介紹:
ord() 函數(shù)是 chr() 函數(shù)(對于 8 位的 ASCII 字符串)的配對函數(shù),它以一個字符串(Unicode 字符)作為參數(shù),返回對應的 ASCII 數(shù)值,或者 Unicode 數(shù)值。
>>> ord('0') 48 >>> ord('A') 65 >>> ord('a') 97
應用實例:
ord()函數(shù)的一個應用場景就是,利用哈希表解決字母異位詞問題。
利用ord()函數(shù)求解每個字母的ASCII數(shù)值,再利用每個字母和字母a之間的差值,將26個小寫英文字母映射到下標分別為0-25的數(shù)組上,數(shù)組中存放的是每個字母的數(shù)目。
例如:
class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ result = [] record_s = [0]*26 record_p = [0]*26 if len(s) < len(p): return result for i in range(len(p)): record_s[ord(s[i])-ord('a')] += 1 record_p[ord(p[i])-ord('a')] += 1 if record_s == record_p: result.append(0) for i in range(len(s)-len(p)): record_s[ord(s[i])-ord('a')] -= 1 record_s[ord(s[i+len(p)])-ord('a')] += 1 if record_s == record_p: result.append(i+1) return result
到此這篇關于python 中內置函數(shù)ord()返回字符串的ASCII數(shù)值的文章就介紹到這了,更多相關python內置函數(shù)ord()ASCII數(shù)值內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python實習總結(yeild,async,azwait和協(xié)程)
今天是Python實習的第一天,熟悉了環(huán)境,第一次使用macbook,氛圍還不錯,努力學習新知識,希望本片文章能給你帶來幫助2021-10-10