新聞中心
str在python中用法
Python中的str可以表示字符串類,也可以是將變量強(qiáng)制轉(zhuǎn)換為字符串的函數(shù),寫作str()。str函數(shù)是Python內(nèi)置函數(shù)的一種,可以直接使用,無需調(diào)用。 擴(kuò)展資料
站在用戶的角度思考問題,與客戶深入溝通,找到越城網(wǎng)站設(shè)計(jì)與越城網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、域名與空間、虛擬空間、企業(yè)郵箱。業(yè)務(wù)覆蓋越城地區(qū)。
python中srt的全稱是SubRip Text,srt文件打開方式srt文件可以使用系統(tǒng)自帶的.文本處理器來打開,比如notepad.exe,write.exe,word等文件處理軟件。在Python中,str 表示字符串類 ,也可以是將變量強(qiáng)制轉(zhuǎn)換為字符串的函數(shù),寫作str()。
python str和repr的區(qū)別
str與repr區(qū)別:
1、python中str函數(shù)通常把對象轉(zhuǎn)換成字符串,即生成對象的可讀性好的字符串,一般在輸出文本時(shí)使用,或者用于合成字符串。str的輸出對用戶比較友好適合print輸出。
2、pyton中repr函數(shù)將一個(gè)對象轉(zhuǎn)成類似源代碼的字符串,只用于顯示。repr的輸出對python友好,適合eval函數(shù)得到原來的對象。
3、在類中實(shí)現(xiàn)__str__和__repr__方法,就可以得到不同的返回,示例代碼:
class?test(object):
def?__repr__(self):
return?"return?test?repr()?string."
def?__str__(self):
return?"return?test?str()?string."
print(str(test()))
return?test?str()?string.
print(repr(test()))
return?test?repr()?string.
python中的__str__函數(shù)作用
__str__方法:總結(jié)
在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法,當(dāng)使用print輸出對象的時(shí)候,只要自己定義了__str__(self)方法,那么就會打印從在這個(gè)方法中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) + "個(gè)輪胎..."
? ??return msg
def move(self):
? ??print('車在跑,目標(biāo):夏威夷')
BMW = Car(4, "白色")
print(BMW)
例子2:如:
class Cat:
"""定義了一個(gè)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("貓?jiān)诔贼~....")
def drink(self):
? ? print("貓正在喝kele.....")
def introduce(self):
? ? print("%s的年齡是:%d"%(self.name, self.age))
#創(chuàng)建一個(gè)對象
tom = Cat("湯姆", 40)
lanmao = Cat("藍(lán)貓", 10)
print(tom)
print(lanmao)
運(yùn)行結(jié)果:
湯姆的年齡是:40
藍(lán)貓的年齡是:10
python str函數(shù)怎么用
是將一個(gè)對象轉(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。
當(dāng)前文章:python中str函數(shù) python 中str
本文網(wǎng)址:http://fisionsoft.com.cn/article/doihdpi.html