成都创新互联网站制作重庆分公司

python的str函数 str函数 python

python中的str函数

上面那个是做合并加法+时的转换,返回的数据如果是整数序列,序列的加法就成了新增整型,并引起错误。而需要的是字符串的合并。

目前成都创新互联已为上千多家的企业提供了网站建设、域名、虚拟空间、网站运营、企业网站设计、大安网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

下面由于print打印函数默认会对最终输入的对象进行repr()字符表示化处理,所以不需要再次转换字符串

python str函数怎么用

是将一个对象转成字符串显示,注意只是显示用,有些对象转成字符串没有直接的意思。

str():将变量转化为字符串类型

a = 1

b = [1, 2, 3]

str_a = str(a)

print(a)

print(type(a))

str_b = str(b)

print(b)

print(type(b))

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by

the interpreter (or will force a SyntaxError if there is not equivalent syntax). For objects which don't have a particular representation for human consumption, str() will

return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings and。

python中的__str__函数作用

__str__方法:总结

在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法,当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据

例子1:如:

class Car:

def __init__(self, newWheelNum, newColor):

    self.wheelNum = newWheelNum

    self.color = newColor

def __str__(self):

    msg = "嘿。。。我的颜色是" + self.color + "我有" + int(self.wheelNum) + "个轮胎..."

    return msg

def move(self):

    print('车在跑,目标:夏威夷')

BMW = Car(4, "白色")

print(BMW)

例子2:如:

class Cat:

"""定义了一个Cat类"""

#初始化对象

def __init__(self, new_name, new_age):

    self.name = new_name

    self.age = new_age

def __str__(self):

    return "%s的年龄是:%d"%(self.name, self.age)

#方法

def eat(self):

    print("猫在吃鱼....")

def drink(self):

    print("猫正在喝kele.....")

def introduce(self):

    print("%s的年龄是:%d"%(self.name, self.age))

#创建一个对象

tom = Cat("汤姆", 40)

lanmao = Cat("蓝猫", 10)

print(tom)

print(lanmao)

运行结果:

汤姆的年龄是:40

蓝猫的年龄是:10

python中str是什么意思?

str函数是Python的内置函数,它将参数转换成字符串类型,其语法格式为str(object),返回object的字符串形式。


网站题目:python的str函数 str函数 python
网站路径:http://cxhlcq.com/article/hiegdp.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部