为什么我们必须在python中编写print('you are ' + str(32) + ' Years old')
,而我们只需要编写print('you are 32 Years old')
来向字符串添加一个整数,并且它们都非常好地工作
是的,如果我们希望它总是打印常量行,我们可以在python中编码为print('you are 32 Years old')
。
当必须从变量中获取32时,如果我们确实知道变量类型是一个字符串,那么我们可以在不进行str((转换的情况下使用它。例如:print('you are ' +x+ ' years old')
当我们不知道变量类型将始终是字符串时,我们需要显式地将其转换为字符串print('you are' +str(x)+ 'years old')
。
如果没有str(x)
,当x是整数时,python会给出以下错误:
>>> x = 32
>>> type(x)
<type 'int'>
>>> print ("you are "+ x + " years old")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> x = "32"
>>> type(x)
<type 'str'>
>>> print ("you are "+ x + " years old")
you are 32 years old
>>>
TLDR:
不能将字符串和整数相加。您必须将整数强制转换为字符串才能添加(连接(它们。
以为这是给C++的
就像alani所说的用express(在你的例子"str(32("中(连接字符串一样,程序可以显示比硬编码更多的内容。
例如,假设您的程序询问用户的姓名和年龄:
#include <iostream>
int main()
{
string name;
int age;
std::cout << "What is your name? n";
std::cin >> name;
std::cout << "What is your age? n";
std::cin >> age;
std::cout << "My name is " << namen";
std::cout << "I am " << age << " years old";
return 0;
在运行时,用户将输入一个字符串(他们的姓名(和一个整数(他们的年龄(,这可能会根据用户输入而改变。
该程序将输出:
My name is: John Smith
I am 32 years old
然而,您的程序是硬编码的,这意味着每次运行它时都会提供相同的输出。
首次运行:
My name is rjt
I am 32 years old
第二次运行:
My name is rjt
I am 32 years old
第n次运行:
My name is rjt
I am 32 years old
现在,将表达式和字符串连接到名称和年龄这样简单的东西可能不太常见,但当你学习更复杂的程序时,你的程序就会出现VITAL。
现在,只需按照教程中的步骤操作,你应该很快就会看到曙光!