Python编程技巧 – 单字符函数

Python编程技巧 – 单字符函数

Python Programming Skills – Single Character Function

By Jackson@ML

0. 前言

Python有其内建(built-in)的一系列函数,其中,有两个函数为长度为一的字符设计。这样的函数是单字符函数,尽管它们操作的对象也是字符串类型。

ord(str)    # 返回一个字符的数字编码
chr(n)     # 将ASCII/Unicode编码转换成单个字符

1. 单字符函数

我们看以下的例子:

>>> str = 'B'
>>> ord(str)
66
>>> n = 66
>>> chr(n)
'B'
>>> n = 70
>>> chr(n)
'F'

可以看到,ord(str)函数接受一个字符串参数(长度等于一)传递,并转换为ASCII或Unicode编码;但是 ,如果str参数长度大于一,则会引发TypeError异常,看下面例子:

>>> s = 'Welcome'
>>> ord(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 7 found
>>>

由于字符串变量被赋值长度为7,超过了1,因此ord()函数报错TypeError.

2. 单字符函数逻辑判断

尽管in和not in运算符支持使用长度大于1的字符串,但是它们经常用于这种字符串判断。我们创建一个新的字符串,并用单字符函数来检测其中包含的元音和辅音字母。

以下代码判断字符串是否包含元音:

>>> s = 'welcome'
>>> i = 0
>>> for i in range(len(s)):
...   if s[i] in 'aeiou':
...     print('Some vowel in the string.')
...
Some vowel in the string.
Some vowel in the string.
Some vowel in the string.

若要提取具体出现在字符串中的元音字母,则修改代码如下:

>>> s = 'welcome'; i = 0
>>> for i in range(len(s)):
...   if s[i] in 'aeiou':
...     print('Some vowel ', s[i], ' in the string')
...
Some vowel  e  in the string
Some vowel  o  in the string
Some vowel  e  in the string

同样,如果判断并提取辅音字母,则使用 not in 逻辑来判断。代码如下所示:

>>> s = 'welcome'; i = 0
>>> for i in range(len(s)):
...   if s[i] not in 'aeiou':
...     print('Some consonant ', s[i], ' in the string')
...
Some consonant  w  in the string
Some consonant  l  in the string
Some consonant  c  in the string
Some consonant  m  in the string

若要判断某个大写字符是否包含在字符串中,则需要做一些处理。我们需要将该字符串在测试字符之前转换成大写即可。

>>> h = 'FAntastIC'; i = 0
>>> for i in range(len(h)):
...   if h[i] in 'AEIOU':
...     print(f'Some capital vowel {h[i]} in the string')
...
Some capital vowel A in the string
Some capital vowel I in the string

在本例中,字符串 h 包含两个大写元音字母,通过筛选最终打印输出到屏幕。

3. 单字符运算迭代

单字符运算在数值迭代中也很重要,比如使用for循环来遍历列表,则其可访问某个列表元素。如果使用for循环来遍历字符串,则会依次访问每个字符(同样为长度为一的字符串,而不是单独的“字符”类型的对象。

示例代码如下:

>>> s = 'Cat'
>>> for ch in s:
...   print(ch, ', type:', type(ch))
...
C , type: <class 'str'>
a , type: <class 'str'>
t , type: <class 'str'>

也正是由于这些字符都是长度为1的字符串,因此,它们可以输出相应的ASCII码,示例代码如下:

>>> s = 'Cat'
>>> for ch in s:
...   print(ord(ch), end=' ')
...
67 97 116 >>>

技术好文陆续推出,敬请关注。

喜欢就点赞哈!您的认可,我的动力。😃

相关阅读:

  1. Python编程技巧 - 使用组合运算符
  2. Python编程技巧 - 异常处理
  3. Python编程技巧 - Lambda函数
  4. Python编程技巧 - 迭代器
  5. Python编程技巧 - 使用字典
  6. Python编程技巧 - 使用字符串(Strings)
  7. Python编程技巧 - 对象和类
  8. Python编程技巧 - 使用列表(Lists)
  9. Python编程技巧 - 转换二进制、八进制和十六进制的函数
  10. Python编程技巧 - 函数入门
  11. 安装2023最新版PyCharm来开发Python应用程序
  12. 安装最新版Visual Studio Code来开发Python应用程序
  13. 2023最新版Python 3.12.0安装使用指南
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值