alk*_*lik -1 python python-3.x
我有以下代码:
store_id = 1
acc_id = str(store_id)
print("type of acc_id is ", type(acc_id))
x = len(acc_id)
print(x)
if len(acc_id == 1):
acc_id += '000' + acc_id
Run Code Online (Sandbox Code Playgroud)
输出:
type of acc_id is <class 'str'>
1
TypeError: object of type 'bool' has no len()
Run Code Online (Sandbox Code Playgroud)
acc_id当显然是一个字符串时,为什么我会收到此错误?
您没有正确检查长度acc_id。
正确的是len(acc_id) == 1.
所以更新后的代码将是:
store_id = 1
acc_id = str(store_id)
print("type of acc_id is ", type(acc_id))
x = len(acc_id)
print(x)
if len(acc_id) == 1:
acc_id += '000' + acc_id
print(acc_id)
Run Code Online (Sandbox Code Playgroud)
acc_id就是现在10001。
您收到错误的原因是:
if 之前的 acc_id = '1'。
acc_id == 1 给出,False因为str和int不是同一类型的操作数
len(False) 给出TypeError,因为没有len()bool 类型。