Is there a good shortcut for modifying python vari

2019-03-07 06:54发布

问题:

i += 1 can be used instead of i = i + 1.

Is there a similar shorthand for string = string.replace(...)?

回答1:

No, because there is no built-in syntax for this.

For a string, you can still use +=:

>>> x = "hello"
>>> x += " world"
>>> x
'hello world'

Because += is defined for strings. There just isn't an assignment operator for replace.



回答2:

The type string supports the += operator. You can write str += "hello" but such shortening does not work for functions. The type string is immutable

A function like string.replace returns a new string and therefore you have to replace it against your old string (if that's what you want).