Weak Type Ability for Python

avi.e.gross at gmail.com avi.e.gross at gmail.com
Wed Apr 12 22:12:27 EDT 2023


As originally written, the question posed has way too many possible answers
but the subject line may give a hint. Forget printing.

The Python statement
1 + "a"

SHOULD fail. The first is an integer and the second is  string. These two
are native Python objects that neither define what to do if they are paired
with an object of the other type on the left or the right.

In any case, what should the answer be? Since "a" has no integer value, it
presumably was intended to be the string "1a".

So why NOT use the built-in conversion and instead of:

print(x+y) # where x=1, y='a'

It should be:

print(str(x) + y)

Could this behavior be added to Python? Sure. I wonder how many would not
like it as it often will be an error not caught!

If you defined your own object derived from string and added a __radd__()
method then the method could be made to accept whatever types you wanted
(such as integer or double or probably anything) and simply have code that
converts it to the str() representation and then concatenates them with, or
if you prefer without, any padding between.

I suspect the OP is thinking of languages like PERL or JAVA which guess for
you and make such conversions when it seems to make sense.

Python does not generally choose that as it is quite easy to use one of so
many methods, and lately an f-string is an easy way as others mentioned.


-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com at python.org> On
Behalf Of Thomas Passin
Sent: Wednesday, April 12, 2023 2:52 PM
To: python-list at python.org
Subject: Re: Weak Type Ability for Python

On 4/12/2023 1:11 PM, Chris Angelico wrote:
> On Thu, 13 Apr 2023 at 03:05, Ali Mohseni Roodbari
> <ali.mohseniroodbari at gmail.com> wrote:
>>
>> Hi all,
>> Please make this command for Python (if possible):
>>
>>>>> x=1
>>>>> y='a'
>>>>> wprint (x+y)
>>>>> 1a
>>
>> In fact make a new type of print command which can print and show strings
>> and integers together.
>>
> 
> Try:
> 
> print(x, y)
> 
> ChrisA

It puts a space between "1" and "a", whereas the question does not want 
the space.  print(f'{x}{y}') would do it, but only works for variables 
named "x" and "y".

As happens so often, the OP has not specified what he actually wants to 
do so we can only answer the very specific question.

-- 
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list