chadybear
chadybear

Reputation: 119

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?

Upvotes: 1

Views: 2276

Answers (4)

Electrons_Ahoy
Electrons_Ahoy

Reputation: 38573

The quotes are there to tell Python that those characters should be interpreted as the contents of a String, not as language syntax.

When you have a variable, Python already knows that the contents are a string. Not only do you not need the quotes, but adding them would confuse Python into thinking that you wanted a string holding the name of the variable.

So, both this:

int('fff',16)

and this:

someNumber = 'fff'
int(someNumber,16)

are doing the same thing as far as the int() function is concerned.

All that being said, int() can take a string or a number for the value, but must have a number for the base. So, since raw_input always returns a string, you'd need to do something more like:

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

Upvotes: 1

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

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

Upvotes: 5

Andrew Clark
Andrew Clark

Reputation: 208405

The result of raw_input() will be a string, I think your issue is actually that base is still a string when you need it to be an integer.

Try the following:

base = raw_input('base? ')
num = raw_input('num? ')
print int(num, int(base))

For example:

>>> base = raw_input('base? ')
base? 16
>>> num = raw_input('num? ')
num? fff
>>> print int(num, int(base))
4095

Upvotes: 3

mgilson
mgilson

Reputation: 309821

The problem isn't quotes. The problem is with data types. int with a base expects an integer base and a string number. So, in your case, you'd use:

int(num,int(base))

This takes the strings which are returned from raw_input and it constructs a suitable base from the base string while leaving num as a string as required by the int function.

Upvotes: 2

Related Questions