James Sapam
James Sapam

Reputation: 16930

Type conversion in Python

Is there a way to convert a Python object from one type to another based on the given value?

>>> first = 1
>>> second = '2'
>>> type(first)
<type 'int'>
>>> type(second)
<type 'str'>

So, I want to convert first to the type of any given second object. I am not really sure how to do this.

Upvotes: 0

Views: 118

Answers (2)

Amaury Larancuent
Amaury Larancuent

Reputation: 323

>>> str(1)
'1'
>>> int('1')
1

Above answer is better, tho

Upvotes: -1

Kevin
Kevin

Reputation: 76184

You could call the type of one of the objects using the other object as a parameter. This doesn't necessarily work for all types, but it does work for your specific example:

>>> first = 1
>>> second = "2"
>>> type(first)(second)
2
>>> type(second)(first)
'1'

This is no different than doing int(second) and str(first), except the types are determined dynamically instead of you specifying them manually.

Upvotes: 10

Related Questions