Search code examples
pythonstringvariablesquotes

putting a variable inside of quotes in python


I have just started learning Python. I am trying to have the user input a number base, and a number, and convert that to decimal.

I've been trying to use the built in int function like this:

base = raw_input("what number base are you starting with?  \n")
num = raw_input("please enter your number:  ")
int(num,base)

My problem is that when you use that int function, the number your converting needs to be in quotes like so: int('fff',16)

How can I accomplish this when im using a variable?


Solution

  • Quotes are not needed. The quotes are not part of the string.

    >>> int('fff',16)
    4095
    >>> da_number = 'fff'
    >>> int(da_number, 16)
    4095
    

    You will, however, need to cast the base to an integer.

    >>> base = '16'
    >>> int(da_number, base) # wrong! base should be an int.
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: an integer is required
    >>> int(da_number, int(base)) # correct
    4095