首页 > 编程知识 正文

Python 中如何将int转换为string

时间:2023-11-25 15:30:09 阅读:309148 作者:EFNQ

我们可以使用 Python 内置的 str() 函数来转换整数数据类型。此函数将任何数据类型作为参数,并将其转换为字符串。但是我们也可以使用“%s”文本并使用。format()函数。下面是 str() 函数的语法。

语法-


str(integer_Value)

让我们理解下面的例子。

示例- 1 使用 str()功能


n = 25
# check  and print type of num variable
print(type(n))
print(n)

# convert the num into string
con_num = str(n)

# check  and print type converted_num variable
print(type(con_num))
print(con_num)

输出:

<class 'int'>
25
<class 'str'>
25

示例- 2 使用“%s”整数


n = 10

# check and print type of n variable
print(type(n))

# convert the num into a string and print
con_n = "% s" % n
print(type(con_n))

输出:

<class 'int'>
<class 'str'>

示例- 3:使用。格式()功能


n = 10

# check  and print type of num variable
print(type(n))

# convert the num into string and print
con_n = "{}".format(n)
print(type(con_n))

输出:

<class 'int'>
<class 'str'>

示例- 4:使用 f 弦


n = 10

# check  and print type of num variable
print(type(n))

# convert the num into string
conv_n = f'{n}'

# print type of converted_num
print(type(conv_n)) 

输出:

<class 'int'>
<class 'str'>

我们已经定义了将整数数据类型转换为字符串类型的所有方法。你可以根据自己的要求使用其中的一种。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。