PHP前端开发

如何在Python中将数字转换为字符串?

百变鹏仔 1个月前 (01-20) #Python
文章标签 转换为

要将一个数字转换为字符串,有多种方法。让我们一一来看。

使用format()将数字转换为字符串

Example

的中文翻译为:

示例

在这个例子中,我们将使用format()方法将一个数字转换为字符串 -

# Integer to be convertedn = 60# Display the integer and it's typeprint("Integer = ",n)print("Type= ", type(n))# Convert the integer to string and display the typemyStr = "{}".format(n)print("String = ", myStr)print("Type = ", type(myStr))

输出

Integer =  60Type=  <class>String =  60Type =  <class></class></class>

使用str()函数将数字转换为字符串

Example

的中文翻译为:

示例

在这个例子中,我们将使用str()方法将一个数字转换为字符串 −

# Integer to be convertedn = 25# Display the integer and it's typeprint("Integer = ",n)print("Type= ", type(n))# Convert the integer to string using str() and display the typemyStr = str(n)print("String = ", myStr)print("Type = ", type(myStr))

输出

Integer =  25Type=  <class>String =  25Type =  <class></class></class>

使用%s格式将数字转换为字符串

Example

的中文翻译为:

示例

在这个例子中,我们将使用%s格式说明符将一个数字转换为字符串−

立即学习“Python免费学习笔记(深入)”;

# Integer to be convertedn = 90# Display the integer and it's typeprint("Integer = ",n)print("Type= ", type(n))# Convert the integer to string using %s and display the typemyStr = "% s" % nprint("String = ", myStr)print("Type = ", type(myStr))

输出

Integer =  90Type=  <class>String =  90Type =  <class></class></class>

使用__str__()将数字转换为字符串

Example

的中文翻译为:

示例

在这个例子中,我们将使用Python中的__string__()方法将一个数字转换为字符串 -

# Integer to be convertedn = 150# Display the integer and it's typeprint("Integer = ",n)print("Type= ", type(n))# Convert the integer to string using __str__() and display the typemyStr = n.__str__()print("String = ", myStr)print("Type = ", type(myStr))

输出

Integer =  150Type=  <class>String =  150Type =  <class></class></class>

使用f-string将数字转换为字符串

Example

的中文翻译为:

示例

在这个例子中,我们将使用 f-string 将一个数字转换为字符串 −

# Integer to be convertedn = 21# Display the integer and it's typeprint("Integer = ",n)print("Type= ", type(n))# Convert the integer to string using f-string and display the typemyStr = f'{n}'print("String = ", myStr)print("Type = ", type(myStr))

输出

Integer =  21Type=  <class>String =  21Type =  <class></class></class>