在Python中增加字符的方法

python中没有数据类型的隐式概念,尽管数据类型的显式转换是可能的,但我们不容易指示运算符以某种方式工作,理解操作数的数据类型,并根据这种方式进行操作。例如 将1添加到一个字符中,如果我们需要增加该字符,则会出现指示类型冲突的错误 因此,需要制定其他方法来增加字符。

null

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)


输出:

Traceback (most recent call last):  File "/home/fabc221bf999b96195c763bf3c03ddca.py", line 9, in     s = s + 1TypeError: 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

说明: 字符转换为字节字符串,递增,然后再次转换为前缀为“’b”的字符串形式,因此第三个值给出正确的输出。 本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享