Is there a good shortcut for modifying python variables using methods?

后端 未结 2 2030
广开言路
广开言路 2021-01-29 14:45

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

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

相关标签:
2条回答
  • 2021-01-29 15:12

    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.

    0 讨论(0)
  • 2021-01-29 15:12

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

    0 讨论(0)
提交回复
热议问题