Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42710

Can we get the following flexibility in Python as In 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?

Upvotes: 4

Views: 371

Answers (4)

John La Rooy
John La Rooy

Reputation: 304215

It looks like page is a str

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

otherwise make page an int

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

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

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

Upvotes: 1

Jim Dennis
Jim Dennis

Reputation: 17500

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).

Upvotes: 1

wisty
wisty

Reputation: 7061

No. Python doesn't have the same level of polymorphism as perl. You can print anything, and mix and match floats and ints quite easily, and lots of things (0, '', "", () and []) all end up False, but no, it's not perl in terms of polymorphism.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

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,)

Upvotes: 7

Related Questions