Python 字符串增量方法
在本教程中,我们将学习在 Python 中递增字符的不同方法。
类型转换
让我们首先看看在不进行类型转换的情况下,将整数添加到字符会发生什么。
示例
## str initialization char = "t" ## try to add 1 to char char += 1 ## gets an error
如果您执行上面的程序,它将产生以下结果:
TypeError Traceback (most recent call last) <ipython-input-20-312932410ef9> in <module>() 3 4 ## try to add 1 to char ----> 5 char += 1 ## gets an error TypeError: must be str, not int
要在 Python 中递增字符,我们必须将其转换为**整数**,然后为其加 1,最后将结果**整数**转换为**字符**。我们可以使用内置方法**ord**和**chr**来实现这一点。
示例
## str initialization
char = "t"
## converting char into int
i = ord(char[0])
## we can add any number if we want
## incrementing
i += 1
## casting the resultant int to char
## we will get 'u'
char = chr(i)
print(f"Alphabet after t is {char}")如果您执行上面的程序,它将产生以下结果:
Alphabet after t is u
字节
还有一种使用**bytes**递增字符的方法。
- 将字符串转换为**bytes**。
- 结果将是一个数组,包含字符串中所有字符的 ASCII 值。
- 为转换后的**bytes**的第一个字符加 1。结果将是一个整数。
- 将**整数**转换为**字符**。
示例
## str initialization
char = "t"
## converting char to bytes
b = bytes(char, 'utf-8')
## adding 1 to first char of 'b'
## b[0] is 't' here
b = b[0] + 1
## converting 'b' into char
print(f"Alphabet after incrementing ACII value is {chr(b)}")如果您执行上面的程序,它将产生以下结果:
Alphabet after incrementing ACII value is u
如果我们有一个字符串并将其转换为**bytes**,那么我们可以递增任何我们想要的字符。让我们来看一个例子。
示例
## str initialization
name = "tutorialspoint"
## converting char to bytes
b = bytes(name, 'utf-8')
## adding 1 to 'a' char of 'b'
## 'a' index is 6
b = b[6] + 1
## converting 'b' into char
print(f"name after incrementing 'a' char is tutori{chr(b)}lspoint")如果您执行上面的程序,它将产生以下结果:
name after incrementing ‘a’ char is tutoriblspoint
我希望您能很好地理解这个概念。如果您对本教程有任何疑问,请在评论区提出。祝您编程愉快 :)
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP