Spot any errors? let me know, but Unleash your pedant politely please.

Friday 29 May 2009

Python: str * int … WTF!? … Thinks … Ah!

I was reading Guido's History of Python blog this morning. In it he mentions this :
Passing an invalid argument, for example a string, is generally caught quickly because few operations accept mixed string/numeric operands (the exception being multiplication)

WTF!?
Rushes over to Terminal...
>>> 'string' *2
'stringstring'

Why the hell would _anyone_ want to do that ?

…Thinks…

…Realise that I have some code that can be simplified with this…
indent=''
for space in range(level):
indent += ' '

…quick check for zero case…
>>> 'string' *0
''

…changes code…
indent = ' ' * level

Python lesson 1 learned for the day.

No comments:

Post a Comment