Python 中的速记添加/追加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/433795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shorthand adding/appending in Python
提问by Teifion
I like that in PHP I can do the following
我喜欢在 PHP 中我可以执行以下操作
$myInteger++;
$myString += 'more text';
With Python I must do the following
使用 Python 我必须执行以下操作
myInteger = myInteger + 1
myString = myString + "more text"
Is there a better way to add or append to a variable in Python?
有没有更好的方法在 Python 中添加或附加到变量?
回答by Jeremy Ruten
Python doesn't have the increment (++) and decrement (--) operators, but it does have the += operator (and -=, etc.) so you can do this:
Python 没有递增 (++) 和递减 (--) 运算符,但它有 += 运算符(和 -= 等),因此您可以这样做:
myInteger += 1
myString += "more text"
回答by hyperboreean
You could do it in the same way you are doing it in PHP:
你可以像在 PHP 中那样做:
var += 1
But my advice is to write it down clear:
但我的建议是把它写清楚:
var = var + 1