[Tutor] string conversion and formatters
Fri, 07 Dec 2001 15:19:48 -0500
I made this change:
elif choice == "b":
hex_string = raw_input("Hex: ")
hex = int(hex_string, 16)
print "Decimal: %d" % (hex)
The raw_input is a string. The %d print format expects an integer.
Fortunately, the int function allows you to specify the base for your string
when converting to integer. You will get an error if you specify a base
larger than 36.
> Hello! I am just beginning to learn programming and
> Python. I am teaching myself using online tutorials
> and documentation. Concerning output formatters...as
> in "%d", "%s", etc. I know I have seen a listing of
> all the types somewhere in the documentation, but for
> the life of me I cannot relocate it. Where can I find
> Now for the real question. Here is my first real
> program. It is supposed to be a decimal/hex
> #Decimal/Hex Convertor
> def print_options():
> print "Options:"
> print " 'a' decimal to hex"
> print " 'b' hex to decimal"
> print " 'c' print options"
> print " 'd' quit"
> choice = "c"
> while choice != "d":
> if choice == "a":
> dec = input("Decimal: ")
> print "Hex: %X" % (dec)
> elif choice == "b":
> hex = raw_input("Hex: ")
> print "Decimal: %d" % (hex)
> elif choice != "d":
> choice = raw_input("option: ")
> If you run this program, it works fine until you try
> to convert hex to decimal. Why does this not work? I
> have tried using "string.atoi" and some other things,
> but no luck. I am stumped. Please, give me some
> explanations or hints to point me in the right
> direction...I would very much appreciate it!
> By the way, I'm using Python2.2 on Windows 98.
> Do You Yahoo!?
> Send your FREE holiday greetings online!
> Tutor maillist - Tutor@python.org
1 Court Street, Suite 378
Lebanon, NH 03766-1358