在本教程中,我们将看到在Python中增加字符的不同方法。
类型转换
首先让我们看看如果在不进行类型转换的情况下向char添加int会发生什么。
示例## str initialization
char = "t"
## try to add 1 to char
char += 1 ## gets an error
如果执行上述程序,它将产生以下结果-TypeError Traceback (most recent call last)
in ()
3
4 ## try to add 1 to char
----> 5 char += 1 ## gets an error
TypeError: must be str, not int
要在Python中增加字符,我们必须将其转换为整数,然后向其加1,然后将结果整数转换为char。我们可以使用内置方法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递增字符的方法。将str转换为字节。
结果将是一个包含字符串所有字符的ASCII值的数组。
将1添加到转换后的字节的第一个char中。结果将是一个整数。
将int转换为char。
示例## 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
如果必须将字符串转换为字节,则可以增加所需的任何字符。让我们看一个例子。
示例## str initialization
name = "nhooo"
## 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
希望您能很好地理解这个概念。快乐编码:)