Can we get the following flexibility in Python as Perl

Unfortunately. I'm not trying to start a flame. My experience with scripts is from Perl, and I'm pretty new to Python.

I just want to check if I can have the same degree of flexibility as in Python.

In Python:

page = form.getvalue("page") str = 'This is string : ' + str(int(page) + 1) 

In Perl:

 $str = 'This is string : ' . ($page + 1); 

Is there any way to avoid int / str conversion?

+4
source share
4 answers

No, because Python is strongly typed. If you save page as int, you can do the following:

 s = 'This is string : %d' % (page + 1,) 
+7
source

It looks like page is str

 page = form.getvalue("page") S = 'This is string : %d'%(int(page)+1) 

otherwise make page a int

 page = int(form.getvalue("page")) S = 'This is string : %d'%(page+1) 

For the record (and to show that this has nothing to do with strong typing), you can also do crazy things like this:

 >>> class strplus(int): ... def __radd__(self, other): ... return str(int(other).__add__(self)) ... >>> page = form.getvalue("page") >>> page + strplus(1) '3' 
+1
source

You can use:

 mystr = "This string is: %s" % (int(page) + 1) 

... string conversion will be automatic when interpolating to %s using % (string formatting operator).

You cannot get around the need to convert from string to integer. Python will never conflict strings for other data types. In different contexts, Python can return a string or “representation” of an object, so there are some implicit data in string forms. (Under the hood, these call methods .__str__() or .__repr__() ).

(Although some people do not like this, I personally think that the concept of % overloading for string interpolation is much more reasonable than a function called sprintf() (if you have a language that supports operator overloading anyway).

+1
source

Not. Python does not have the same level of polymorphism as perl. You can print anything, as well as easily mix and match float and ints, and many things (0, '', "", () and []) end in False, but no, it's not perl in terms of polymorphism.

0
source

Source: https://habr.com/ru/post/1301074/


All Articles