python中函数str python中函数strip

str在python中用法Python中的str可以表示字符串类,也可以是将变量强制转换为字符串的函数,写作str() 。str函数是Python内置函数的一种,可以直接使用,无需调用 。扩展资料
python中srt的全称是SubRip Text,srt文件打开方式srt文件可以使用系统自带的.文本处理器来打开,比如notepad.exe,write.exe,word等文件处理软件 。在Python中,str 表示字符串类,也可以是将变量强制转换为字符串的函数,写作str() 。
python中的__str__函数作用__str__方法:总结
在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法,当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
例子1:如:
class Car:
def __init__(self, newWheelNum, newColor):
self.wheelNum = newWheelNum
self.color = newColor
【python中函数str python中函数strip】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 string函数python string函数是什么?一起来看下吧python中函数str:
python string函数包括:
1、str.capitalize:将原字符串内的首字母转成大写,其他部分小写,再返回新字符串
print("s.capitalize() = {function}"s.capitalize() = Abcada a
2、str.lower:将原字符串的字母转为小写
print("s.lower() = {function}".format(function = s.lower()))s.lower() = abcada a
3、str.upper:将原字符串的字母转为大写
print("s.upper() = {function}".format(function = s.upper()))s.upper() = ABCADA A
4、str.swapcase:将原字符串的大写小写反转
print("s.swapcase() = {function}".format(function = s.swapcase()))s.swapcase() = ABCAdA A
5、str.title:原字符串内如果有特殊字符(包括数字)连接字母,则将特殊字符后的首个英文字母转化为大写形态,并返回新字符串
print("s2.title() = {function}".format(function = s2.title()))s2.title() = 123A Abc Abcsaa S
6、str.center:str.center(宽度,填充字符) 将字符串以居中的格式返回,若宽度值比len(s)小则返回原字符串,填充以从左到右为规则,填充字符的默认值为空格,值可以自己更改
print("s2.center() = {function}".format(function = s2.center(19,'')))print("s2.center() = {function}".format(function = s2.center(20,'')))#s2 = 123a abc ABCSAa ss2.center() = 123a abc ABCSAa ss2.center() = 123a abc ABCSAa s
7、str.expandtabs:str.expandtabs(tabsize = 8) 将原字符串中 以前的字符补满8位(默认),tabsize的值从0-7即8位,在0-7中任意取值则默认tabsize = 8,此后往上+1python中函数str,就相当于增加一个空格
print("s3.expandtabs ={function}".format(function = s3.expandtabs()))print("s3.expandtabs ={function}".format(function = s3.expandtabs(0)))print("s3.expandtabs ={function}".format(function = s3.expandtabs(5)))print("s3.expandtabs ={function}".format(function = s3.expandtabs(8)))print("s3.expandtabs ={function}".format(function = s3.expandtabs(9)))#s3 = " asb123"s3.expandtabs =asb123s3.expandtabs =as b123s3.expandtabs =asb123s3.expandtabs =asb123s3.expandtabs =as

推荐阅读