python 整型转字符串_如何在Python中将整数转换为字符串

本文介绍了如何将Python整数转换为字符串。

Python有几种内置数据类型。有时,在编写Python代码时,您可能需要将一种数据类型转换为另一种数据类型。例如,连接一个字符串和整数,首先,您需要将整数转换为字符串。

Pythonstr()函数

在Python中,我们可以使用内置str()函数将整数和其他数据类型转换为字符串。

该str()函数返回给定对象的字符串版本。它采取以下形式:

class str(object='')

class str(object=b'', encoding='utf-8', errors='strict')

object -要转换为字符串的对象。

该函数接受三个参数,但是通常,当将整数转换为字符串时,仅将一个参数(object)传递给该函数。

将Python整数转换为字符串

要将整数23转换为字符串版本,只需将数字传递给str()函数:

str(23)

type(days)

输出:

'23'

23周围的引号表示数字不是整数,而是字符串类型的对象。此外,该type()函数还显示该对象是字符串。

在Python中,使用单引号()',双"引号(""")或三引号()声明字符串。

连接字符串和整数

让我们尝试使用+运算符将字符串和整数连接起来并输出结果:

number = 6

lang = "Python"

quote = "There are " + number + " relational operators in " + lang + "."

print(quote)

Python将引发TypeError异常错误,因为它无法连接字符串和整数:

Traceback (most recent call last):

File "", line 1, in

TypeError: can only concatenate str (not "int") to str

要将整数转换为字符串,请将整数传递给str()函数:

number = 6

lang = "Python"

quote = "There are " + str(number) + " relational operators in " + lang + "."

print(quote)

现在,当您运行代码时,它将成功执行:

There are 6 relational operators in Python.

还有其他方式来连接字符串和数字。

内置字符串类提供了format()一种使用任意一组位置和关键字参数来格式化给定字符串的方法:

number = 6

lang = "Python"

quote = "There are {} relational operators in {}.".format(number, lang)

print(quote)

输出

There are 6 relational operators in Python.

在Python 3.6及更高版本上,您可以使用f字符串,即以'f'为前缀的文字字符串,其中的括号内包含表达式:

number = 6

lang = "Python"

quote = f"There are {number} relational operators in {lang}."

print(quote)

输出:

There are 6 relational operators in Python.

最后,您可以使用旧的%格式:

number = 6

lang = "Python"

quote = "There are %s relational operators in %s." % (number, lang)

print(quote)

输出:

There are 6 relational operators in Python.

结论

在Python中,您可以使用str()函数将整数转换为字符串。

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值