目錄
零基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
一.Python ord 函數介紹
** ord 函數是以單個字符作為參數,返回對應的 ASCll 數值或者 Unicode 值,如果所給的 Unicode 字符超出了你的 Python 定義范圍,則會引發一個 TypeError 的異常**。語法如下:
'''
參數介紹:
c — 是一個單字符,長度為1,例如:‘a’/‘b’/‘c’/‘d’/‘e‘等等
返回值 — 對應的十進制整數(ASCll數值)
'''
ord(c)
注意:ord 函數的參數是單個字符,並非多個,則會引發 TypeError 異常!!
二.Python ord 函數使用
案例 1
>>>ord('a')
97
>>>ord('b')
98
>>>ord('c')
99
案例 2
# !usr/bin/env python
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python ord 函數.py
@Time:2021/04/21 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
str=input("請輸入任意字符:")
yin=shu=kong=qita=0
for i in str:
# 小寫字母a~z的ascall碼對應為:65-91
# 大寫字母A~Z的ascall碼對應為:97-123
if(ord(i)>=97 and ord(i)<=122) or (ord(i)>=65 and ord(i)<=90):
yin=yin+1
elif ord(i)>=48 and ord(i)<=57:
shu=shu+1
elif ord(i)==32:
kong=kong+1
else:
qita=qita+1
print("英文字母個數:{}個".format(yin))
print("數字個數:{}個".format(shu))
print("空格個數:{}個".format(kong))
print("其他字符個數:{}個".format(qita))
'''
輸出結果:
請輸入任意字符:dfsd fgdfghfhfg jh
英文字母個數:16個
數字個數:0個
空格個數:3個
其他字符個數:0個
'''
三.猜你喜歡
- Python for 循環
- Python 字符串
- Python 列表 list
- Python 元組 tuple
- Python 字典 dict
- Python 條件推導式
- Python 列表推導式
- Python 字典推導式
- Python 函數聲明和調用
- Python 不定長參數 *argc/**kargcs
- Python 匿名函數 lambda
- Python return 邏輯判斷表達式
- Python 字符串/列表/元組/字典之間的相互轉換
- Python 局部變量和全局變量
- Python type 函數和 isinstance 函數區別
- Python is 和 == 區別
- Python 可變數據類型和不可變數據類型
- Python 淺拷貝和深拷貝
未經允許不得轉載:猿說編程 » Python ord 函數
本文由博客 - 猿說編程 猿說編程 發布!