Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we get the following flexibility in Python as In Perl

Tags:

python

perl

Sorry. I am not trying to start any flame. My scripting experience is from Perl, and I am pretty new in Python.

I just want to check whether 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 I can avoid int / str conversion?

like image 212
Cheok Yan Cheng Avatar asked Jan 22 '23 14:01

Cheok Yan Cheng


2 Answers

No, since Python is strongly typed. If you keep page as an int you can do the following:

s = 'This is string : %d' % (page + 1,)
like image 135
Ignacio Vazquez-Abrams Avatar answered Jan 30 '23 13:01

Ignacio Vazquez-Abrams


You could use:

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

... the string conversion will be automatic when interpolating into the %s via the % (string formating operator).

You can't get around the need to convert from string to integer. Python will never conflate strings for other data types. In various contexts Python can return the string or "representation" of an object so there are some implicit data casts into string forms. (Under the hood these call .__str__() or .__repr__() object methods).

(While some folks don't like it I personally think the notion of overloading % for string interpolation is far more sensible than a function named sprintf() (if you have a language with operator overloading support anyway).

like image 38
Jim Dennis Avatar answered Jan 30 '23 13:01

Jim Dennis