小编uns*_*le2的帖子

与 += 运算符一起使用字符串和整数的对象

Python中有没有一种方法可以初始化一个变量,以便它可以与+= "a string"或一起工作+= 100使用?\n例如:

\n
a = <what to put here>\na += 100  # a = 100\nb = <same what to put here from above>  \nb += "a string"  # b = "a string"\n
Run Code Online (Sandbox Code Playgroud)\n

如果我使用:

\n
a = ""\na += "a string"  # this will work fine\nb = ""\nb += 0  # -> TypeError\n
Run Code Online (Sandbox Code Playgroud)\n

一旦定义了变量的类型,TypeError如果我尝试+=不同的类型,之后就可以得到 a 。例如:

\n
a = <what to put here>\na += "a string"  # a = …
Run Code Online (Sandbox Code Playgroud)

python

6
推荐指数
2
解决办法
197
查看次数

标签 统计

python ×1