当前位置:   article > 正文

Python编程技巧 – 单字符函数

Python编程技巧 – 单字符函数

Python编程技巧 – 单字符函数

Python Programming Skills – Single Character Function

By Jackson@ML

0. 前言

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

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

1. 单字符函数

我们看以下的例子:

>>> str = 'B'
>>> ord(str)
66
>>> n = 66
>>> chr(n)
'B'
>>> n = 70
>>> chr(n)
'F'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

可以看到,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
>>>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

由于字符串变量被赋值长度为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.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

>>> 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

同样,如果判断并提取辅音字母,则使用 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

>>> 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在本例中,字符串 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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

>>> s = 'Cat'
>>> for ch in s:
...   print(ord(ch), end=' ')
...
67 97 116 >>>
  • 1
  • 2
  • 3
  • 4
  • 5

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/44626
推荐阅读
相关标签