📜  在Python中增加字符的方法

📅  最后修改于: 2022-05-13 01:54:19.581000             🧑  作者: Mango

在Python中增加字符的方法

在Python中并没有隐含的数据类型概念,虽然数据类型的显式转换是可以的,但是我们并不容易指示运算符以某种方式工作并理解操作数的数据类型并据此进行操作。比如给一个字符加1,如果我们需要增加一个字符,就会出现一个错误指示类型冲突,因此需要制定其他的方法来增加字符。

Python
# python code to demonstrate error
# due to incrementing a character
 
# initializing a character
s = 'M'
 
# trying to get 'N'
# produces error
s = s + 1
 
print (s)


Python3
# python code to demonstrate way to
# increment character
 
# initializing character
ch = 'M'
 
# Using chr()+ord()
# prints P
x = chr(ord(ch) + 3)
 
print ("The incremented character value is : ",end="")
print (x)


Python3
# python code to demonstrate way to
# increment character
 
# initializing byte character
ch = 'M'
 
# converting character to byte
ch = bytes(ch, 'utf-8')
 
# adding 10 to M
s = bytes([ch[0] + 10])
 
# converting byte to string
s = str(s)
 
# printing the required value
print ("The value of M after incrementing 10 places is : ",end="")
print (s[2])


输出:

Traceback (most recent call last):
  File "/home/fabc221bf999b96195c763bf3c03ddca.py", line 9, in 
    s = s + 1
TypeError: cannot concatenate 'str' and 'int' objects

使用 ord() + chr()

Python3

# python code to demonstrate way to
# increment character
 
# initializing character
ch = 'M'
 
# Using chr()+ord()
# prints P
x = chr(ord(ch) + 3)
 
print ("The incremented character value is : ",end="")
print (x)

输出:

The incremented character value is : P

解释: ord() 返回字符对应的 ASCII 值,加上整数后,chr() 再次将其转换为字符。

使用字节字符串

Python3

# python code to demonstrate way to
# increment character
 
# initializing byte character
ch = 'M'
 
# converting character to byte
ch = bytes(ch, 'utf-8')
 
# adding 10 to M
s = bytes([ch[0] + 10])
 
# converting byte to string
s = str(s)
 
# printing the required value
print ("The value of M after incrementing 10 places is : ",end="")
print (s[2])

输出:

The value of M after incrementing 10 places is : W