tags:

views:

250

answers:

2

I like that in PHP I can do the following

$myInteger++;
$myString += 'more text';

With Python I must do the following

myInteger = myInteger + 1
myString = myString + "more text"

Is there a better way to add or append to a variable in Python?

+11  A: 

Python doesn't have the increment (++) and decrement (--) operators, but it does have the += operator (and -=, etc.) so you can do this:

myInteger += 1
myString += "more text"
yjerem
Yay me for never actually attempting += after finding that ++ wouldn't work...
Teifion
@Teifion: and yay twice for never skimming through the Python documentation.
ΤΖΩΤΖΙΟΥ
Side note: you should generally prefer ''.join(['some', 'more text', 'to add']) to += for strings with more than 2 components.
cdleary
A: 

You could do it in the same way you are doing it in PHP:

var += 1

But my advice is to write it down clear:

var = var + 1
hyperboreean
I find the first one is WAY clearer. And it avoids a possible typo where you would accidently do something else than increment var.
PEZ
var = var + 1 is not clearer.
too much php
muhuk
I wouldn't down vote someone for saying it's subjective, but correct opinion.
hyperboreean