0

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.

2
  • As pointe out below, you can do this but it won't work for any given type. Are you asking out of curiosity or is there a specific use case? Commented Apr 28, 2017 at 18:49
  • Ya i ve use case for query mongodb base on the given value. like query for "False" is different than querying boolean (false). Commented Apr 28, 2017 at 18:56

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

awesome :) thank you so much i lost around 2 hours thinking about that.
Ya my types are dynamic.
-1
>>> str(1) '1' >>> int('1') 1 

Above answer is better, tho

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.