Python为啥会报错 类型 'str' 没有预期的特性 '__sub__'
时间: 2023-12-24 10:05:28 浏览: 12
这是因为在Python中,字符串类型(str)是不支持减法运算的。当你使用字符串类型进行减法运算时,Python会尝试调用字符串类型的__sub__方法,但是这个方法并不存在,因此就会报错。
如果你想进行字符串的拼接操作,可以使用加法运算符(+),或者使用join()方法。如果你真的需要进行字符串的减法运算,你可以将字符串转化为数字类型,进行减法运算后再将结果转化为字符串类型。
相关问题
类型 'str' 没有预期的特性 '__sub__'
这个报错信息通常表示您在尝试对一个字符串对象执行减法操作。在Python中,字符串对象是不支持减法操作的,因为减法操作对于字符串的意义不明确。
如果您需要对字符串执行减法操作,您需要先将字符串转换为适当的数值类型,例如整数或浮点数。只有在这种情况下,才能对字符串执行减法操作。
如果您只是想将两个字符串拼接在一起,您可以使用加号操作符,例如:
```
str1 = 'Hello'
str2 = 'World'
result = str1 + str2
print(result) # 输出 'HelloWorld'
```
如果您需要对字符串执行其他操作,例如替换、拆分或格式化等,您可以查阅Python官方文档或其他相关教程来学习如何正确使用字符串操作函数。
报错AttributeError: 'str' object has no attribute 'copy'
根据提供的引用内容,报错"AttributeError: 'str' object has no attribute 'copy'"是因为在代码中使用了字符串对象的copy方法,而字符串对象没有copy方法。要解决这个问题,你可以使用字符串的切片操作来复制字符串。下面是一个示例代码:
```python
def encrypt(m, k):
k_sub = generate_k_sub(k)
ip_displace = displace(m, IP_substitution) # 初始置换
ipl = [] # L列表
r = [] # R列表
for i in range(0, 16):
l_temp = r[i - 1]
r_temp = xor(l_temp, f(r[i - 1], k_sub[i]))
ipl.append(l_temp)
r.append(r_temp)
result = r[16] + l[16]
c = displace(result, IP_inverse_substitution)
return c
def decrypt(c, k):
k_sub = generate_k_sub(k)
ip_displace = displace(c, IP_substitution) # 初始置换
ipl = [] # L列表
r = [] # R列表
for i in range(0, 16):
l_temp = r[i - 1]
r_temp = xor(l_temp, f(r[i - 1], k_sub[15 - i]))
ipl.append(l_temp)
r.append(r_temp)
result = r[16] + l[16]
m = displace(result, IP_inverse_substitution)
return m
def bin_to_hex(bin_str):
# 将64位二进制字符串分割为每个字节(8位)
bytes_list = [bin_str[i:i+8] for i in range(0, len(bin_str), 8)]
# 每个字节转换为对应的十六进制表示
hex_str = ''.join(format(int(byte, 2), '02X') for byte in bytes_list)
return hex_str
if __name__ == '__main__':
num = int(input().strip())
M = input().strip()[2:]
K = input().strip()[2:]
plaintext = encrypt(M, K)
plaintext = plaintext.zfill(64)
print('0x' + bin_to_hex(plaintext).lower())
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)