我们可以使用 str()
方法将数字转换为字符串,然后将数字值转换为字符串值。
要将整数)`方法:
1str(12)
1[secondary_label Output]
2'12'
数字12
周围的引用意味着数字不再是整数,而是现在是一个字符串值。
通过变量,我们可以开始看到将整数转换为字符串是多么实用。假设我们想要跟踪用户的日常编程进度,并且正在输入他们同时写的代码的行数。
1user = "Sammy"
2lines = 50
3
4print("Congratulations, " + user + "! You just wrote " + lines + " lines of code.")
当我们运行此代码时,我们会收到以下错误:
1[secondary_label Output]
2TypeError: Can't convert 'int' object to str implicitly
我们无法在Python中连接字符串和整数,所以我们必须将变量字符串转换为字符串值:
1user = "Sammy"
2lines = 50
3
4print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of code.")
现在,当我们运行代码时,我们收到以下输出,祝贺我们的用户的进展:
1[secondary_label Output]
2Congratulations, Sammy! You just wrote 50 lines of code.
如果您想了解更多关于转换Python数据类型的信息,请参阅我们的(https://andsky.com/tech/tutorials/how-to-convert-data-types-in-python-3)教程,您还可以在我们的(How To Code in Python 3)(https://www.digitalocean.com/community/tutorial_series/how-to-code-in-python-3)系列中找到更多的Python主题。