python中的str()函数

it2022-05-08  14

1.python中的str()用来避免数据类型匹配错误 例如: 运行下列代码

num=19960223 info="my name is z,my birthday is" message=num+info+"!" print(messge)

输出:

C:\Users\Bianca\AppData\Local\Programs\Python\Python37\python.exe C:/Users/Bianca/PycharmProjects/test_1.py Traceback (most recent call last): File "C:/Users/Bianca/PycharmProjects/test_1.py", line 3, in <module> message=num+info+"!" TypeError: unsupported operand type(s) for +: 'int' and 'str' Process finished with exit code 1

traceback显示类型错误。int数据类型和str类型 那么该怎么解决这种错误呢?

使用str()函数,可以将非字符串类型转换成字符串;

正确使用,只需要将message=num+info+"!"改成message=str(num)+info+"!"


最新回复(0)