Python中reverseBits函数报错ValueError及行号异常问题排查
Let’s break down the two issues you’re facing and how to resolve them:
1. The ValueError: Unknown format code 'b' for object of type 'str'
This error occurs because you’re passing a string to the reverseBits method instead of an integer. The format specifier 'b' is meant to convert integers to their binary string representation—when you pass a string (like "123" instead of 123), Python can’t apply the 'b' code to it, hence the error.
To fix this:
- Ensure you call the method with an integer argument (e.g.,
obj.reverseBits(10)instead ofobj.reverseBits("10")). - If you need to handle string inputs, add a conversion check at the start of the method:
def reverseBits(self, n): if isinstance(n, str): n = int(n) # Rest of your code...
2. The Mysterious Line 20 Error
The line number in the traceback refers to the line in your full source file, not just the snippet you shared. Since your reverseBits method is part of a class (evidenced by the self parameter), the actual line where '{0:08b}'.format(n) is written is line 20 in your entire file—even though it’s only the second line in your snippet. That’s why the line number seems mismatched.
3. Fixing the Return Value Issue
Even if you resolve the input type error, your current code returns a reversed iterator object, which isn’t a usable result for reversing bits. You need to convert that iterator back to a string, then to an integer. Here’s the corrected full method:
def reverseBits(self, n): # Ensure input is an integer if not isinstance(n, int): raise TypeError("Input must be an integer (or convertible to one)") # Convert n to an 8-bit binary string (padded with leading zeros) binary = '{0:08b}'.format(n) # Reverse the binary string (join the reversed iterator into a string) reversed_binary = ''.join(reversed(binary)) # Convert the reversed binary string back to an integer return int(reversed_binary, 2)
Example Usage:
# For n = 10 (binary: 00001010) obj.reverseBits(10) # Returns 80 (binary: 01010000)
内容的提问来源于stack exchange,提问作者Daniel Paczuski Bak

