Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #38502
| References | <90002ad8-06fe-42d3-a463-a43c0b2401aa@googlegroups.com> |
|---|---|
| Date | 2013-02-09 21:43 +1100 |
| Subject | Re: Coercing one object to type of another |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1534.1360406617.2939.python-list@python.org> (permalink) |
On Sat, Feb 9, 2013 at 9:29 PM, Vijay Shanker <deontics@gmail.com> wrote:
> Hi
> Inside a function i get a two arguments, say arg1 and arg2, how can i convert arg2 to same type as arg1 ?
> I dont know type of arg1 or arg2 for that matter, I just want to convert arg2 to type of arg1 if possible and handle the exception if raised.
> Also:
>>>> int('2')
> 2
>>>> float('2.0')
> 2.0
>>>> coerce(2,2.0)
> (2.0,2.0)
> but coerce('2',2) fails.If int('2') equals 2, why should it fail ?
You can get the type of any object, and call that:
def coerce(changeme,tothis):
return type(tothis)(changeme)
ChrisA
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Coercing one object to type of another Vijay Shanker <deontics@gmail.com> - 2013-02-09 02:29 -0800
Re: Coercing one object to type of another Chris Angelico <rosuav@gmail.com> - 2013-02-09 21:43 +1100
Re: Coercing one object to type of another Vijay Shanker <deontics@gmail.com> - 2013-02-09 03:23 -0800
Re: Coercing one object to type of another Chris Angelico <rosuav@gmail.com> - 2013-02-09 22:31 +1100
Re: Coercing one object to type of another Vijay Shanker <deontics@gmail.com> - 2013-02-09 03:23 -0800
Re: Coercing one object to type of another Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-10 08:11 +1100
csiph-web