I tried for the last hour to do a basic thing with list, but it doesn't work, and I can't find out why
x = -5000
code = (str("{:07.0f}".format(abs(x)))
if code[3] == 5:
print("1")
else:
print("2")
When I run this, the value in code is 0005000. If I do print(code_background_x[3])
, the output will be 5, but when I. run the program, the output is 2. What am I doing wrong here?
You forgot to enclose the 5
in quotes.
This works for me:
x = -5000
code = str("{:07.0f}".format(abs(x)))
if code[3] == "5":
print("1")
else:
print("2")
Prints: 1
You are comparing a str
type object with int
. It's apparent that types of both are not same. Probably you will wish to compare with '5'
x = -5000
code = (str("{:07.0f}".format(abs(x))))
if code[3] == 5:
print("1")
else:
print("2")
print(type(code[3]))
print(type(5))
code[3]
is "5"
, not 5
. Type of "5"
is str
while type of 5
is int
. You can use builtin type function for getting type of any object, which is good for debugging.
x = -5000
code = str("{:07.0f}".format(abs(x)))
print(type(code[3])) # <class 'str'>
print("5" == 5) # False
You can also use repr for debugging when you encounter this type of problems. It returns printable representation of an object.
x = -5000
code = str("{:07.0f}".format(abs(x)))
print("5") # 5
print(5) # 5
print(repr("5")) # '5'
print(repr(5)) # 5
So this works:
x = -5000
code = str("{:07.0f}".format(abs(x)))
if code[3] == '5':
print("1")
else:
print("2")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.