Heim >Backend-Entwicklung >Python-Tutorial >Python 中为何没有数字到字符串的自动转换?
print " I am " + 10 + "years old " will raise error . but it is ok in many other languages. Java,eg.
Explicit is better than implicit.
只有在数字类型中才存在类型转换
在Python中,一个诸如123+3.145的表达式是可以工作的——它会自动将整数型转换为浮点型,然后用浮点运算。但是下面的代码就会出错了:
S = "42"
I = 1
X = S + I # 类型错误
这同样也是有意而为的,因为这是不明确的:究竟是将字符串转换为数字(进行相加)呢,还是将数字转换为字符串(进行联接)呢?在Python中,我们认为“明确比含糊好”(即,EIBTI(Explicit is better than implicit)),因此你得手动转换类型:
X = int(S) + I # 做加法: 43
X = S + str(I) # 字符串联接: "421"
<code class="language-php"><span class="cp"><?php </span>
<span class="k">echo</span> <span class="s1">'Result:'</span><span class="o">.</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="mi">2</span><span class="o">+</span><span class="mi">3</span><span class="p">);</span>
<span class="cp">?></span><span class="x"></span>
</span></code>
python 是一门强类型语言,强类型自然有强类型的好处。<code class="language-js"><span class="p">({</span><span class="nx">valueOf</span><span class="o">:</span><span class="kd">function</span><span class="p">(){</span><span class="k">return</span> <span class="mi">1</span><span class="p">;}}</span><span class="o">+</span><span class="p">{</span><span class="nx">valueOf</span><span class="o">:</span><span class="kd">function</span><span class="p">(){</span><span class="k">return</span> <span class="mi">1</span><span class="p">;}})</span><span class="c1">//猜猜等于几?</span>
</code>
题目本身只涉及强弱类型和字符串连接,不过有回答把问题扩展到 print/echo 以及运算符了。<code class="language-python"><span class="mi">1</span> <span class="o">!=</span> <span class="s">'1'</span>
</code>