简体   繁体   English

尝试剥离“ 0x”时出错

[英]Error trying to strip "0x'

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? 我正在尝试使用下面的代码剥离十六进制值中的“ 0x”并遇到错误,有人可以建议如何解决它吗?

   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返回一个字符串值:

>>> hex(123)
'0x7b'
>>> type(hex(123))
<class 'str'>
>>>

but format is expecting a hexadecimal value as its first argument: 但是format期望十六进制值为第一个参数:

>>> 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: 相反,您可以通过切片去除0x

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. [2:]将获取字符串中除前两个字符以外的所有字符。 See a demonstration below: 请参见下面的演示:

>>> hex(123)
'0x7b'
>>> hex(123)[2:]
'7b'
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM