python ord()與chr()用法

1 ord()函數

主要用來返回對應字符的ascii碼

print(ord("a"))  # 97

2 chr()函數

主要用來表示ascii碼對應的字符他的輸入時數字,可以用十進制,也可以用十六進制。

print(chr(97))  # a

3 一個簡單的程序來靈活運用。

# 以下程序主要實現對字符串str1裏面所有的字符,轉換成ascii碼中比他們小一位的字符。
str1 = 'asdfasdf123123'
str2 = ""
for i in range(len(str1)):
    str2 += chr(ord(str1[i]) - 1)

print(str2)

應用:可以用來生成隨機驗證碼:

import random


def make_code(size=7):
    res = ''
    for i in range(size):
        # 循環一次則得到一個隨機字符(字母/數字)
        s = chr(random.randint(65, 90))
        num = str(random.randint(0, 9))
        res += random.choice([s, num])
    return res


res = make_code()
print(res)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章