python如何增加字符串_在python中增加字符的方法

在本教程中,我们将看到在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

希望您能很好地理解这个概念。快乐编码:)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值