Python ord 函数 - Python零基础入门教程

目录

零基础 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个
'''

三.猜你喜欢

  1. Python for 循环
  2. Python 字符串
  3. Python 列表 list
  4. Python 元组 tuple
  5. Python 字典 dict
  6. Python 条件推导式
  7. Python 列表推导式
  8. Python 字典推导式
  9. Python 函数声明和调用
  10. Python 不定长参数 *argc/**kargcs
  11. Python 匿名函数 lambda
  12. Python return 逻辑判断表达式
  13. Python 字符串/列表/元组/字典之间的相互转换
  14. Python 局部变量和全局变量
  15. Python type 函数和 isinstance 函数区别
  16. Python is 和 == 区别
  17. Python 可变数据类型和不可变数据类型
  18. Python 浅拷贝和深拷贝

未经允许不得转载:猿说编程 » Python ord 函数

本文由博客 - 猿说编程 猿说编程 发布!