Python Forum

Full Version: The 'b' Word
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Another Project I Am Working On Here The Problem Is:
How To Remove That 'b' Word In Binary
Output:
Please Type The Number: 0x3 The 0x3 In Decimal Number Is = 3 The 0x3 In Binary Number Is = 0b11
Here Is The Source Code
#All Bases Start Here
#All Bases End Here
def IsNumericBase(s, base):
 try:
  int(s, base)
  return True
 except ValueError:
  return False
def isDeci(s):
    return IsNumericBase(s, 10)
# Returns True if <s> is binary number string
def IsBinaryString(s):
 return IsNumericBase(s, 2)

# Returns True if <s> is octal number string
def IsOctalString(s):
 return IsNumericBase(s, 8)

# Returns True if <s> is hexadecimal number string
def IsHexadecimalString(s):
 return IsNumericBase(s, 16)

#Main Def Starting
def maincheck(temp):
    a = isDeci(temp)
    if a == False:
        b = IsBinaryString(temp)
        if b == False:
            oc = IsOctalString(temp)
            if oc == False:
                hexa = IsHexadecimalString(temp)
                if hexa == False:
                    print("Only Hex,Numbers,Binary And Octal Are Supported")
                else:
                    print("The " + str(temp) +" In Decimal Number Is = ",int(temp, 16))
                    print("The " + str(temp) +" In Binary Number Is = ",bin(int(temp,16)))
            else:
                print("Is " + str(temp) +" Octal Number? = ",hexa)
        else:
            print("Is " + str(temp) +" Binary Number? = ",b)
    else:
        print("Is " + str(temp) +" Decimal Number? = ",a)
#Main Def Ending 

if __name__ == "__main__":
    print("\t\tWelcome To Hex_To_Decimal_Binary_Octal\n")
    #for i in range(1,6):
    temp = input("Please Type The Number: ")
    maincheck(temp)
If you have a string that you know is '0b...' or '0x...' how do you print just the '...' part? Look at slices.
Use string formatting
spam = 3
print(bin(spam))
print(f'{spam:b}')
Output:
0b11 11
also looking at the docs for bin():
https://docs.python.org/3/library/functions.html#bin

Quote:If prefix “0b” is desired or not, you can use either of the following ways.
>>>format(14, '#b'), format(14, 'b')
('0b1110', '1110')

>>>f'{14:#b}', f'{14:b}'
('0b1110', '1110')
See also format() for more information.
Hey! This Problem Now Another Problem When I Type 0b01 in decimal it is saying 2817 i don't know why!
0b01 hexadecimal (base 16) is 2817 in decimal (base 10)
(Aug-12-2020, 08:41 AM)buran Wrote: [ -> ]0b01 hexadecimal (base 16) is 2817 in decimal (base 10)

Hey! Thanks For Telling I Found The Wrong It was set int(temp,16) that's Why it tells me wrong