上面那個是做合并加法+時的轉(zhuǎn)換,返回的數(shù)據(jù)如果是整數(shù)序列,序列的加法就成了新增整型,并引起錯誤。而需要的是字符串的合并。
目前成都創(chuàng)新互聯(lián)已為上千多家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬空間、網(wǎng)站運營、企業(yè)網(wǎng)站設(shè)計、大安網(wǎng)站維護等服務(wù),公司將堅持客戶導向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
下面由于print打印函數(shù)默認會對最終輸入的對象進行repr()字符表示化處理,所以不需要再次轉(zhuǎn)換字符串
是將一個對象轉(zhuǎn)成字符串顯示,注意只是顯示用,有些對象轉(zhuǎn)成字符串沒有直接的意思。
str():將變量轉(zhuǎn)化為字符串類型
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。
__str__方法:總結(jié)
在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法,當使用print輸出對象的時候,只要自己定義了__str__(self)方法,那么就會打印從在這個方法中return的數(shù)據(jù)
例子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))
#創(chuàng)建一個對象
tom = Cat("湯姆", 40)
lanmao = Cat("藍貓", 10)
print(tom)
print(lanmao)
運行結(jié)果:
湯姆的年齡是:40
藍貓的年齡是:10
str函數(shù)是Python的內(nèi)置函數(shù),它將參數(shù)轉(zhuǎn)換成字符串類型,其語法格式為str(object),返回object的字符串形式。
名稱欄目:python的str函數(shù) str函數(shù) python
網(wǎng)站鏈接:http://sd-ha.com/article18/hiegdp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗、網(wǎng)站設(shè)計公司、App開發(fā)、、網(wǎng)站營銷、域名注冊
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)