Error trying to strip "0x' - python

I am trying to strip of "0x" form the hex value using below code and running into error,can anyone suggest how to fix it?
with open(r'\\Network\files\build_ver.txt','r+') as f:
value = int(f.read(), 16)
f.seek(0)
write_value = hex(value + 1)
final_value = format(write_value, 'x')
f.write(final_value)
Error:-
Traceback (most recent call last):
File "build_ver.py", line 5, in <module>
final_value = format(write_value, 'x')
ValueError: Unknown format code 'x' for object of type 'str'

The hex built-in returns a string value:
>>> hex(123)
'0x7b'
>>> type(hex(123))
<class 'str'>
>>>
but format is expecting a hexadecimal value as its first argument:
>>> format('0x7b', 'x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'x' for object of type 'str'
>>>
>>> format(0x7b, 'x')
'7b'
>>>
Thus, it cannot be used here. Instead, you can just strip off the 0x with slicing:
with open(r'\\Network\files\build_ver.txt','r+') as f:
value = int(f.read(), 16)
f.seek(0)
write_value = hex(value + 1)[2:]
f.write(write_value)
[2:] will get every character in the string except for the first two. See a demonstration below:
>>> hex(123)
'0x7b'
>>> hex(123)[2:]
'7b'
>>>

Related

dictionary TypeError: 'int' object is not callable

I have this code:
def function_factory(x,y,o):
d = {'+':x+y,'-':x-y,'*':x*y,'/':x/y,'%':x%y}
for k,v in d.items():
if o == k:
return v
So if I input print(function_factory(3,4,'*')) then what I would expect to get is 12 but instead I get this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
Test.assert_equals(function_factory(2,3,'+')(), 5)
TypeError: 'int' object is not callable
I tried a different way of doing it but I still get this error. Thank you very much in advance.
first you should not call your function result and insted assert the it: function_factory(2,3,'+') and not function_factory(2,3,'+')() just as #Sayse said in comments
second, your function will tell you what is the operation to get the result.. not the result of a operation:
if this is your intention, you should use it like this:
function_factory(2,5,10)
>>> '*'
function_factory(2,5,7)
>>> '+'
function_factory(2,5,-3)
>>> '-'
function_factory(2,5,2/5)
>>> '/'
in case you want to make it work as you expect,and not as i showed you how it is already working, you should change your function:
def function_factory(x,y,o):
d = {'+':x+y,'-':x-y,'*':x*y,'/':x/y,'%':x%y}
return d[o]
and then the result would be :
function_factory(3,4,'*')
>>> 12

How to put a space between two characters in an Input given by the user?Where is my mistake??(I am a beginner

# Read an integer:
a = int(input())
# Print a value:
print(a[0] + " " + a[1])
As you can see that I am trying to put a space using a string but I am having an error which is as follows:
Traceback (most recent call last):
File "python", line 4, in <module>
TypeError: 'int' object is not subscriptable

list index out of range in my coding

Can anyone help me fix this error I keep getting please. I have tried to look for a solution but I can't find any. Below is the error message and also part of my coding
Please enter your class Y or X or Z: Y
Traceback (most recent call last):
File "/Volumes/LIAM'S USB/DEV6 FINAL.py", line 118, in <module>
score=int(items[1])
IndexError: list index out of range
results={
start=True
while (start):
pupil_class=input("\nPlease enter your class Y or X or Z: ")
if pupil_class == ("Y"):
classfile="Class_Y_results.txt"
elif pupil_class == ("X"):
classfile="Class_X_results.txt"
elif pupil_class == ("Z"):
classfile="Class_Z_results.txt"
f=open(classfile,'r')
for line in f:
items=line.split(',')
name=items[0]
score=int(items[1])
if name in results:
results[name].append(score)
else:
results[name]=[]
results[name].append(score)
f.close()
A certain line in your Class_Y_Results.txt only has one entry (not separated by commas), hence the list returned by items=line.split(',') only has a length of 1 (or maybe 0), causing score=int(items[1]) to throw an IndexError.
Sample:
>>> a = "foo,bar"
>>> b = "foo"
>>> len(a.split(','))
2
>>> len(b.split(','))
1
>>> a.split(',')[1]
'bar'
>>> b.split(',')[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
There is probably an empty like in one of your files. This will not contain a comma, so you will not have an item[1], and this produces the error message you see.
Check how many fields you get back from the split to solve this.

Python format with variable digits count

So, I can do:
>>> '%.4x' % 0x45f
'045f'
But I need to pass 4 from variable, smth like
>>> digits=4
>>> '%.'+str(digits)+'x' % 0x45f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
The % operator has a higher precedence than +, so you need to put the first part in parenthesis:
>>> digits = 4
>>> ('%.'+str(digits)+'x') % 0x45f
'045f'
>>>
Otherwise, 'x' % 0x45f will be evaluated first.
However, the modern approach is to use str.format for string formatting operations:
>>> digits = 4
>>> "{:0{}x}".format(0x45f, digits)
'045f'
>>>

Why is this giving me an index error in python?

In the code below, s refers to a string (although I have tried converting it to a list and I still have the same problem).
s = "".join(s)
if s[-1] == "a":
s += "gram"
I the last item in the string is the letter "a", then the program needs to add the string "gram" to the end of the string 's' represents.
e.g. input:
s = "insta"
output:
instagram
But I keep getting an IndexError, any ideas why?
If s is empty string s[-1] causes IndexError:
>>> s = ""
>>> s[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Instead of s[-1] == "a", you can use s.endswith("a"):
>>> s = ""
>>> s.endswith('a')
False
>>> s = "insta"
>>> s.endswith('a')
True
If s is empty, there is no last letter to test:
>>> ''[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Use str.endswith() instead:
if s.endswith('a'):
s += 'gram'
str.endswith() does not raise an exception when the string is empty:
>>> 'insta'.endswith('a')
True
>>> ''.endswith('a')
False
Alternatively, using a slice would also work:
if s[-1:] == 'a':
as slices always return a result (at minimum an empty string) but str.endswith() is more self-evident as to what it does to the casual reader of your code.

Categories