网站开发编程,海外推广,wordpress 个人博客模板,建筑兼职网站Python编程技巧 – 单字符函数
Python Programming Skills – Single Character Function
By JacksonML
0. 前言
Python有其内建(built-in)的一系列函数#xff0c;其中#xff0c;有两个函数为长度为一的字符设计。这样的函数是单字符函数#xff0c;尽管它们操作的对象…Python编程技巧 – 单字符函数
Python Programming Skills – Single Character Function
By JacksonML
0. 前言
Python有其内建(built-in)的一系列函数其中有两个函数为长度为一的字符设计。这样的函数是单字符函数尽管它们操作的对象也是字符串类型。
ord(str) # 返回一个字符的数字编码
chr(n) # 将ASCII/Unicode编码转换成单个字符1. 单字符函数
我们看以下的例子 str Bord(str)
66n 66chr(n)
Bn 70chr(n)
F可以看到ordstr函数接受一个字符串参数长度等于一传递并转换为ASCII或Unicode编码但是 如果str参数长度大于一则会引发TypeError异常看下面例子 s Welcomeord(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 welcomei 0for 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 0for 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 0for 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 0for i in range(len(h)):
... if h[i] in AEIOU:
... print(fSome 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 Catfor ch in s:
... print(ch, , type:, type(ch))
...
C , type: class str
a , type: class str
t , type: class str也正是由于这些字符都是长度为1的字符串因此它们可以输出相应的ASCII码示例代码如下 s Catfor ch in s:
... print(ord(ch), end )
...
67 97 116 技术好文陆续推出敬请关注。
喜欢就点赞哈您的认可我的动力。
相关阅读
Python编程技巧 - 使用组合运算符Python编程技巧 - 异常处理Python编程技巧 - Lambda函数Python编程技巧 - 迭代器Python编程技巧 - 使用字典Python编程技巧 - 使用字符串(Strings)Python编程技巧 - 对象和类Python编程技巧 - 使用列表(Lists)Python编程技巧 - 转换二进制、八进制和十六进制的函数Python编程技巧 - 函数入门安装2023最新版PyCharm来开发Python应用程序安装最新版Visual Studio Code来开发Python应用程序2023最新版Python 3.12.0安装使用指南