来自python的【str字符串内置函数】

字符串内置函数–capitalize

  • str.capitalize():将字符串转换成大写,其他字母变成小写

  • capitalize 含义

 capitalize(...)
 |      S.capitalize() -> str  #输出是一个字符串
 |      
 |      Return a capitalized version of S, i.e. make the
 		first character have upper case and the rest lower case.
 	  #返回一个首字母大写的字符串,即让第一个字母大写,其余字母小写
  • 首字符会转换成大写,其余的都会转换成小写,针对的就是第一个字符而言
  • 首字符如果是非字母,则保持不变,并且其余的都会变成小写
# capitalize 如何查 数据类型的方法
print('helloWorld111'.capitalize())# Helloworld111
print('Hello World 123'.capitalize()) # 不是单词第一个大写哦
print('1HelloWowW'.capitalize())#1hellowoww 起始是数字也不行 就是默认第一位。
print('~!heEW'.capitalize())

字符串内置函数–center

  • str.center(width[,fillchar]) :定义一个width宽度的字符串,使数据居中显示,其余部分使用fillchar进行填充,如果未定义,默认为空格填充。

  • 参数至少为一个,最多为两个,str.center() 会报错 TypeError: center() takes at least 1 argument (0 given)

  • 会在width中居中显示,如果不是居中,那么前短后长哦~

  • fillchar 默认是空格,如果有参数,只能是一个字符,不然会报错The fill character must be exactly one character long

  • 如果width<str.len 会原样输出,并且也不会填充,也不会截取

  • help 输出的内容:

 center(...)
 |      S.center(width[, fillchar]) -> str  # 输出是一个字符串
 |      #s.center(宽度,填充字符) 填充字符是可选的吧
 |      Return S centered in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
# fillchar
print('111111111111111111111111')#24
print('hello'.center(24))
print('hello'.center(3,'1')) # hello
print('hello'.center(10,'-'))
print('hello'.center(10,'*'))
#print('hello'.center(10,'ss')) #The fill character must be exactly one character long

字符串内置函数–count()

  • str.count(sub,start,end) ,搜索sub字符串在str字符串(statr,end)之间重复出现的个数
    start,end是可选参数,默认是statr=0,end=len(str)
  • sub字符的个数是没有限制的,必须是完全一样的才算是出现的个数 否则不算哦
  • start,end左闭右开的取值方式哦!也就是左边start的取值是可以取值的,但是end的取值不行
  • 是否也有负数的statr,end
  • 如果不想填start好像不能省略,会报错invalid syntax
  • start,end的取值要求与索引一样,与之前的切片取值是一样的哦!
  • help的解释
count(...)
 |      S.count(sub[, start[, end]]) -> int  # 输出是一个整形
 |      
 |      Return the number of non-overlapping occurrences of substring sub in string S[start:end].
 	# 返回字符串中出现字串 出现的次数
   Optional arguments start and end are interpreted as in slice notation.
   #可选参数start end 被解释为切片符号,也就是起始和结束
 |  
  • 验证代码
# count
counts = '01234567891111222233333444dddasabcd'
print(counts.count('1')) #5 0 - len(str)
print(counts.count('0',1))#0
print(counts.count('1',0,1)) #0 end 不取
print(counts.count('1',1,2))# 1 statr 取
print(counts.count('aa')) #0
print(counts.count('asa'))#
print(counts.count('asaaa'))#0
print(counts.count('a',0,-2))#2
print(counts.count('a',0,-4))#-1

字符串内置函数–bytes.decode()/str.encode

  • 含义:以指定的编码格式解码byte对象,默认‘utf-8’
  • bytes.decode('encodeing="utf-8",errors'strict'') 可以直接写等号右边的值
  • encodeing 是使用的编码,errors是设置不同错误的处理方式

默认为 ‘strict’,意为编码错误引起一个UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’,
‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error()
注册的任何值。

  • 使用decode解码之前 都是要先编码的str.encode('encoding'),因为decode是针对byte对象进行处理的,所以要先转换成byte对象。否者报错'str' object has no attribute 'decode'
  • str.encode 是对字符串进行编码,注意字符串是要进行编码之后才可以进行解码。
str = '这是'
enstr= str.encode('utf-8')
print(str.encode('utf-8')) #b'\xe8\xbf\x99\xe6\x98\xaf'
print(enstr.decode('utf-8')) # 这是

字符串内置函数–endswith()/startswidth()

  • str.endswith(suffix,start,end) 检测在start,end范围内,字符串是否以suffix内容作为结尾,返回的是一个bool布尔值True/False。
  • start,end是切片位置,左闭右开 (取值范围),end是取不到的
  • suffix的取值类型:suffix 必须是str,或者是只含有字符串的元祖endswith first arg must be str or a tuple of str, not int
  • start,end 的默认情况 ,是否可以省略
  • str.startswith(suffix,start,end),用法相同,检测是否以规定的子字符串开头,返回True/False
 endswith(...) # 字符串字段以这个结尾
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      # s.endswith('可以理解为内容',statr,end)
 |      Return True if S ends with the specified suffix,False otherwise.
 #如果S以指定的后缀结尾,则返回True,否则返回False。
 |      With optional start, test S beginning at that position.With optional end, stop comparing S at that position.#选择切片范围
 |      suffix can also be a tuple of strings to try.
 		# 后缀可以是一个元组 元组如下
 		#tup1 = ('Google', 'Runoob', 1997, 2000)
		#tup2 = (1, 2, 3, 4, 5, 6, 7 )
 |  
# endswith
str3 = '123abcd!!!'
print(str3.endswith('!'))# true
print(str3.endswith('!!'))#true
print(str3.endswith('!!!'))#true
print(str3.endswith(('!!!!!')))#false
print(str3.endswith('a'))#false
print(str3.endswith('a',0))#false
print(str3.endswith('a',0,1))#true
print(str3.endswith('c',1,3))#true end取不到
#print(str3.endswith((1)))

# 元组
strtup = '123abcd123!!!'
#print(strtup.endswith(((1,2,3)))) typeerror
print(strtup.endswith(('1','2','3'))) #true 必须 字符串
# 顺序不一样怎么办
print(strtup.endswith(('2','1','3','!'))) #true
print(strtup.endswith(('@','!')))#false
print(strtup.endswith(('!','1','2','!','3')))#true?
print(strtup.endswith(('!','1','2','!','3'),0,-4))#true
# 自助排列??
print('?')
print(strtup.endswith(('!','2','!'),0,-4))#true 

字符串内置函数–endswith() /startswith() 带元组

  • suffix参数如果是元组,那么必须是字符串类型的,我感觉和元祖的类型有关系,目前还没学,后面补
  • 如果suffix参数是元组,元组内容的顺序没有关系,也就是说,只要在start,end范围之内,元组内只要包含了末尾的后缀,就返回false,如果元组的范围大于末尾也没有关系,只要元组内容是字符串类型,并且在切片范围内,含有后根词缀即可返回true ,也就是遍历元祖中的内容,含有及true。
  • str.endswith('') 输出 都是true
# 元组
strtup = '123abcd123!!!'
#print(strtup.endswith(((1,2,3)))) typeerror
print(strtup.endswith(('1','2','3'))) #true 必须 字符串
# 顺序不一样怎么办
print(strtup.endswith(('2','1','3','!'))) #true
print(strtup.endswith(('@','!')))#false
print(strtup.endswith(('!','1','2','!','3')))#true?
print(strtup.endswith(('!','1','2','!','3'),0,-4))#true
# 自助排列??
print('?')
print(strtup.endswith(('!','2','!'),0,-4))#true 

字符串内置函数–expandtabs()

  • str.expandtabs(n) 将str 语句中的tab\t 转换成n个空格,类似文本缩进。
  • \t 是 tab键,测试的时候要输入
  • 从第一个\t(起始)到下一个\t 之间的字符串+空格 等于8的整数倍 例:abcde\tabd 这里的\t会转换成3个空格,因为前面是5位。 ;又可以abc\tabd这里\t就会补5个空格~
  • 在tabsize<=8 的时候都是以补8个为准,大于8的时候才会按照数字增加。
  • 但是在python3中,是补4的整数倍。
  • help中显示
 expandtabs(...)
 |      S.expandtabs(tabsize=8) -> str  # 返回字符串
 |      
 |      Return a copy of S where all tab characters are expanded using spaces.
 # 将字符串中的制表符号 \t 全部变成 控股
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 #如果tab键的大小没有给定,默认是8 
# expandtabs
extabs = 'abcdefghijklmnopqrstuvwxyz'
print(extabs)
extabst ='\tabcde\tfghijklmnopqrstuvwxyz'
print(extabst)
print(extabst.expandtabs(4))
print(extabst.expandtabs(8)) # 默认是8
print(extabst.expandtabs(9))
print(extabst.expandtabs(12))
print(extabst.expandtabs(16))
'''
abcdefghijklmnopqrstuvwxyz
	abcde	fghijklmnopqrstuvwxyz
    abcde   fghijklmnopqrstuvwxyz
        abcde   fghijklmnopqrstuvwxyz
         abcde    fghijklmnopqrstuvwxyz
            abcde       fghijklmnopqrstuvwxyz
                abcde           fghijklmnopqrstuvwxyz
'''

字符串内置函数–find()

  • str.find(sub,start,end) , sub为要搜索的内容,start,end是切片区间
  • start,end,左闭右开,默认值是0,和len(str),end可省略,start不能单独省略
  • sub字符串必须要全部完全一样才行,个数没有限制
  • 如果statr end可以是负数,逆向获取,但是start一定是小于end的,不然一定返回-1,因为获取不到
  • sub不存在返回-1,sub必须是字符串类型
  • 返回值是数字,输出的index都是正顺序,无论start,end是正数还是负数。
  • 从左到右进行查找,查找sub 第一次出现的位置
 find(...)
 |      S.find(sub[, start[, end]]) -> int
 |      # 查找字符串中是否有sub字符串。并且返回首字母的索引位置,不包含就返回-1,返回的是整数
 |      Return the lowest index in S where substring sub is found,
 	# 如在字符串中找到sub,则返回第一个首字母的索引,最低索引,那就是如果逆向寻找呢?
 |      such that sub is contained within S[start:end].  Optionalarguments start and end are interpreted as in slice notation.
 # start,end 是切片,意味着边值就是start取,end不取
 |      Return -1 on failure.
 #  不存在就返回-1
#str.find
strfind = 'abcdefg111@1aba!!!'
print(strfind.find('a'))#0
#print(strfind.find(1) ) must be str.not int
print(strfind.find('ab')) #0
print(strfind.find('ac'))#-1 不能组合
print(strfind.find('ab',-6,-1))#12
print(strfind.find('ab',-1,-6))#-1 不能逆序
print(strfind.find('!',-1,-6)) # 这样是不存在  start end不合法
#输出的位置都是正序的

字符串内置函数–rfind()

  • str.rfind(sub,start,end) , sub为要搜索的内容,start,end是切片区间
  • start,end,左闭右开,默认值是0,和len(str),end可省略,start不能单独省略.查找最后一个出现的位置,
  • sub字符串必须要全部完全一样才行,个数没有限制
  • 如果statr end可以是负数,逆向获取,但是start一定是小于end的,不然一定返回-1,因为获取不到
  • sub不存在返回-1,sub必须是字符串类型
  • 返回值是数字,输出的index都是正顺序,无论start,end是正数还是负数。
  • str.find是一样的,find查找第一个,rfind查找最后一个
 rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
# rfind 查找最后一个出现的位置
rdn =  'abcdedd!!hh111@@!!'
print(rdn.rfind('1')) #13
print(rdn.rfind('@',8,-1))#15
print(rdn.rfind('@',16,-1))#-1
print(rdn.rfind('@',-3,-1))#15
print(rdn.rfind('@',-1,-3))#-1

字符串内置函数–index()/rindex()

  • 功能与find一致,直接换index即可,只不过找不到的时候index是返回ValueError: substring not found,并且会导致程序终止,不执行
  • rindex是查找最后一个,index查找查找第一个,找不到是报not found
 index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      # 返回index类型,和find方法类似,报错不一样,找不到会返回一个异常 not found
 |      Return the lowest index in S where substring sub is found, 
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 # ValueError
strindex = 'abcdefg111@1aba!!!'
print(strindex.index('a'))#0
#print(strfind.find(1) ) must be str.not int
print(strindex.index('ab')) #0
#print(strindex.index('ac'))#-1 不能组合ValueError: substring not found
print(strindex.index('ab',-6,-1))#12
#print(strindex.index('ab',-1,-6))#-1 不能逆序
#print(strindex.index('!',-1,-6)) # 这样是不存在  start end不合法
#输出的位置都是正序

str.find() 与 str.index() 区别

功能一样,只不过当找不到内容的时候,返回方式不一样。find返回的是-1,并且不会影响后面程序执行;index返回valueError,并且后面程序停止报错。

字符串内置函数–isalnum()

  • str.isalnum() str至少有一个字符 ,字符串只有字母、数字组成(汉字)是true
  • str没有字符,是空字符串的话,返回false
  • 汉字算字符哦,返回True
  • 字母不区分大小写
  • 转义符号等字符false
  • 空字符串是false
 isalnum(...)
 |      S.isalnum() -> bool
 |      # 判断字符串是否由 字母和数字组成 返回的是bool布尔值
 |      Return True if all characters in S are alphanumeric
 |      and there is at least one character in S, False otherwise.
 
 # s中至少有一个字符,
 |  
print(''.isalnum())# false
print('\t'.isalnum()) #false
print('\000'.isalnum())#false
print('00\\'.isalnum())#false
print('和'.isalnum())#true
print('HHhh'.isalnum())#true
print('H12h@'.isalnum())#false
print('0.0'.isalnum())#false
print('\x16'.isalnum())#false
#print(('1','2').isalnum())  元组等不具有这个方法

字符串内置函数–isalpha()

  • str.isalpha() str是否只由文字、字母组成,不包含数字哦、不包含符号,但是文字是true
  • 空字符串、转义字符是、是false
  • 至少要有一个字符
isalpha(...)
 |      S.isalpha() -> bool
 |      # 检测字符串是否只由字母和文字组成 bool 类型
 |      Return True if all characters in S are alphabetic
 |      and there is at least one character in S, False otherwise.
# isalpha
print('isalpha')
print(''.isalpha()) #false
print('哈'.isalpha())#true
print('1'.isalpha()) #false
print('hh'.isalpha())#true
print('11hh'.isalpha())#false
print('11哈哈'.isalpha()) #false
print('@@'.isalpha())#false
print('\n'.isalpha())#false

字符串内置函数–isdigital()

  • str.isdigital() 检测字符串是否只有数字组成,并且至少要有一个字符
  isdigit(...)
 |      S.isdigit() -> bool
 |      # 判断是否只有字符串组成
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
 |  # 至少要有一个字符
#isdigit
print('isdigit')
print(''.isdigit())#false
print('False'.isdigit())#false
print('hh'.isdigit())#falsep
print('11'.isdigit())#true
print('11tt'.isdigit())#false
print('@'.isdigit()) #false
print('哈哈'.isdigit()) #false

字符串内置函数–islower()/isupper()

  • str.islower() 至少有一个字符,并且都是小写
  • 这里的意思是,无论str字符串中包含了什么数据内容,只要是包含的字母,并且都是小写就会输出true
  • 如果str的内容都是非小写字符,或者没有小写字符,都是返回false
  • str.isupper() 与islower()相反,只要含有字母,并且都是大写就会返回True。
  islower(...)
 |      S.islower() -> bool
 |      # 是否由小写字母组成 返回bool值
 |      Return True if all cased characters in S are lowercase and there is  at least one cased character in S, False otherwise.
 #字符串中至少有一个字符串,并且全部都是小写,返true,否则false
 |    
# islower
print('islower')
print(''.islower())#false
print('1'.islower())#false
print('A'.islower())#false
print('a'.islower())#true
print('aA'.islower())#false
print('!'.islower())#false
print('11a'.islower())#true
print('哈哈'.islower())#false
print('哈哈11aaa'.islower())#true
print('@@1a'.islower())#true

字符串内置函数–isnumeric()

  • str.isnumeric() 方法检测字符串是否只由数字组成,数字可以是: Unicode 数字,全角数字(双字节),罗马数字(例子:VI)*,汉字数字(例子:二),但是不识别字节。
    指数类似 ² 与分数类似 ½ 也属于数字。
  • 'bytes' object has no attribute 'isnumerice' 字节不行哦
 isnumeric(...)
 |      S.isnumeric() -> bool
 |      # isnumeric 返回bool 
 |      Return True if there are only numeric characters in S,False otherwise.
	# 只有数字就返回数字 否则就是false
# 这里的数字符号 都是编码来写
#s = '²3455'
s = '\u00B23455'
print(s.isnumeric())
# s = '½'
s = '\u00BD'
print(s.isnumeric())

a = "\u0030" #unicode for 0
print(a.isnumeric())

b = "\u00B2" #unicode for ²
print(b.isnumeric())

c = "10km2"
print(c.isnumeric())

print('a'.isnumeric())#false
print('1'.isnumeric())#true
#print(b'1'.isnumerice())  no
print('\u00B23455'.isnumeric())#true
print('四'.isnumeric())#true
print('叁'.isnumeric())#true
print('三df'.isnumeric())#false

字符串内置函数–isdecimal()

  • str.isdecimal() 判断字符串是否只包含十进制字符串,只能unicode对象,返回True/False
 isdecimal(...)
 |      S.isdecimal() -> bool
 |      
 |      Return True if there are only decimal characters in S,False otherwise.
print('12'.isdecimal())#true
print('a'.isdecimal())#false
print(u'a123'.isdecimal())#False

isdigital/isnumeric/isdecimal 区别

后补

字符串内置函数–isspace()

  • str.isspace() 检测字符串是否只由空白字符组成 空白字符就是能够输出空格的,包含:空格、制表符(\t)、换行(\n) 回车(\r)
  • 空字符串‘’ 输出false
  • 退格键盘 删除到只剩空格也不行,还是返回false
isspace(...)
 |      S.isspace() -> bool
 |      # 
 |      Return True if all characters in S are whitespace
 |      and there is at least one character in S, False otherwise.
 # 字符串中是否只包含空格 是true 不是false
 |  
print('space')
print(''.isspace())#false
print('\r'.isspace())#true
print('\t'.isspace())#true
print('1\t'.isspace())#false
print('\n'.isspace())#true
print(' '.isspace())#true
print('1\b'.isspace())#false
print(' 1\b'.isspace())#false

字符串内置函数–istitle() /title()

  • 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写,以非字母的后一个字符是否为大写为判断依据print('H1h'.istitle())#False
  • 返回值为True/False
  • 可以有其他字母,并且是空格隔开 是一个整体,无论里面有几个单词,都只能首字母大写,不然输出False,HelloHi 这种就算一个单词,每一个单词都需要大写Hell hi 这样会返回False,以非字母的后一个字符是否为大写为判断依据
  • 前面可以有其他的字符,只要第一个遇到的字母是大写,其余是小写的字符串,就true
  • 缩写的均为大写,返回的也是False,例如SOS
  • 不会自动转换为首字母大写的形式
istitle(...)
 |      S.istitle() -> bool
 		# 判断单词首字母大写 其他为小写 返回bool型
 		#并且至少要有一个字符
 |      
 |      Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones.
 # 小写字符只能跟在大写字符后面 
 |      Return False otherwise.
# istitle
print(''.istitle())#false
print('1F'.istitle())#True
print('FatherHi'.istitle())#False
print('1@Father'.istitle())#true
print('Hi hllo'.istitle())#False
print('SOS'.istitle())#False
  • str.title() 将所有单词的首字母化成大写,其余均为小写
  • 非字母后面的第一个字符会变成大写 ,以次用来改变。那么判断也是这样判断,非字母后第一个字符为大写,就是trueprint('H1h'.istitle())#False
  • 返回的是字符串类型
  title(...)
 |      S.title() -> str
 |      
 |      Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case.
 #返回一个有标题的版本的S,即单词以标题大小写字符开头,所有其余的大小写字符都是小写的。
#title
print('Ti hb1H!178js)-2hk 哈哈hjau'.title())
#Ti Hb1H!178Js)-2Hk 哈哈Hjau

字符串内置函数–join(sequence)

  • str.join(sequence) sequence是要被链接的序列,str是分隔符。
  • str作为分隔符,必须要是字符串类型,内容可以随意,可长可短,也可以是单词
  • sequence定义的是可迭代类型,所以字符串序列、集合、元祖、列表都可以使用 (后面需要补),但是可迭代的数据必须是字符串形式,里面含有别的数字类型也是不行的。
  • 返回字符串形式,并且连空格都是会被分割的
  • 分隔不会影响原数据
  • 所有的类型都可以转换成字符类型 可以使用join进行类型转换
join(...)
 |      S.join(iterable) -> str
 |      # iteable 是可迭代数据哦 那可能就不仅仅是字符串
 |      Return a string which is the concatenation of the strings in the iterable.  The separator between elements is S.
 #返回一个字符串,该字符串是iterable中的字符串的串联。元素之间的分隔符是S
s1 = '-'
s2='1'
s3='---'
s4=1
seq = 'hello world' # 字符串的所有都会被分割
print(s1.join(seq))#h-e-l-l-o- -w-o-r-l-d
print(s2.join(seq))#h1e1l1l1o1 1w1o1r1l1d
print(s3.join(seq))#h---e---l---l---o--- ---w---o---r---l---d
#print(s4.join(seq)) #AttributeError: 'int' object has no attribute 'join'
# 属性错误 只能是字符串形式 可以多个
print(s3.join(set('123')))# 1---3---2 可迭代的都可以
print(s3.join(('1','2')))#1---2
#print(s3.join(('1','2',1,2))) #可迭代的字符串内容
# 元组 集合 序列 都可以
# 所有的类型都可以转换成字符类型 可以使用join进行类型转换

字符串内置函数–len()

  • len() 方法返回对象(字符、列表、元组等)长度或项目个数。
  • len()是内置函数,返回对象的长度(元素个数)。实参可以是序列(如 string、bytes、tuple、list 或 range 等)或集合(如 dictionary、set 或 frozen set 等)。len()不是字符串类的方法 需要区分后补
#len
print(len(seq))#11
print(len(s3))#3

字符串内置函数–ljust() 方法/rjust()

  • str.ljust(width,[fillchar]) 返回的是字符串形式,width是定义字符串长度,fillchar是填充字符,填充物默认是空格
  • 返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串
  • 与格式化%str.center功能很像,都是按照宽度走,center是剧中对齐,%是添加精度位数,ljust是左对齐
  • fillchar的要求 TypeError: The fill character must be exactly one character long 填充物只能是单字符
  • 不会影响原数据
  • str.rjust
 ljust(...)
 |      S.ljust(width[, fillchar]) -> str
 |      # width 宽度,fillchar 填充物 默认是字符串
 |      Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).
 #在长度宽度为Unicode的字符串中,返回左对齐的。填充是使用指定的填充字符完成的(默认是空格)。
 |  
# str.ljust
print('hello'.ljust(10,'-'))#hello-----
print(s3.ljust(30,'0'))#---000000000000000000000000000
#print('hello'.ljust(30,'--'))

字符串内置函数–zfill()

  • str.zfill(width) ,返回的是字符串,返回指定width的字符串,并且右对齐,前面填充0,只能填充0 吧
  • 永远不会截断字符串
  • width不填原样输出 小于原本字符串长度,也原样输出。
  zfill(...)
 |      S.zfill(width) -> str
 |      Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.
 # 左边补充0去填充至width,字符串右对齐。并且不会截断,保留原始字符串

字符串内置函数–lower() 方法/upper()

  • str.lower() 返回的是字符串,将字符串中大写字符串转换成小写
  • 是否影响原本数据
  • islower 是判断是否字符都是小写lower是全部转换成小写
  • 只会将大写进行转换,其余字符不变
  • 其他类型没有这个方法,只能序列吧 'set' object has no attribute 'lower'
  • 不会改变原本原数据
  • str.upper() 讲小写字母转换为大写字母,
  • str.swapcase 大小写转换
 lower(...)
 |      S.lower() -> str
 |      Return a copy of the string S converted to lowercase.
 
 upper(...)
 |      S.upper() -> str
 |      
 |      Return a copy of S converted to uppercase.
 #返回转换为小写字符串的副本
# lower
print('lower')
slow = 'H1H2hhh@1}}!!'
slow2 = set('123hHHHH')
print(slow.lower())#h1h2hhh@1}}!!
#print(slow2.lower())#'set' object has no attribute 'lower'

字符串内置函数–swapcase()

  • str.swapcase() 将对字符串中大小写字母进行转换,返回一个字符串类型,不影响原本的数据,输出的是副本
  • 汉字、空字符串都是原样输出
  
 |  swapcase(...)
 |      S.swapcase() -> str
 |      Return a copy of S with uppercase characters converted to lowercase and vice versa.
 # 大小写转换 并且是给一个副本
# swapcase
print('abcABC!!!###%%%'.swapcase())#ABCabc!!!###%%%
print(''.swapcase())#''
print('哈哈'.swapcase())#哈哈

字符串内置函数–lstrip()方法/rstrip()/strip

  • str.lstrip([chars]) 用于截取字符串左边的空格或者是指定字符,chars用于定义指定字符吧,不定义chars的时候,是默认删除空格
  • :/n, /r, /t, ' ') 默认删除的是造成空白的内容
  • chars截去的必须是字符串类型哦1
  • 如果开头有n个chars字符,那么就会被截取n个,不会剩余 '1122'.lstrip('1') 输出’22’
  • chars 的内容,不一定都会被截取,但是如果字符串的左边是有,就会删除print('11223344'.lstrip('21s'))#3344 没有的就忽略 有的就删除,一旦循环排除chars内容后,则停止
  • str.rstrip 是截取字符串右边的数据 与lstrip相反
  • 直到遇到第一个不包含在其中的字符为止
  lstrip(...)
 |      S.lstrip([chars]) -> str 3 返回字符串
 |      Return a copy of the string S with leading whitespace removed.# 返回删除了空格的字符串副本,所以就是不影响原本的数据
 |      If chars is given and not None, remove characters in chars instead. # 如果提供了字符而不是没有字符,则删除字符中的字符
#lstrip
print('lstrip')
strip1 = '!!123@#abcd'
strip2 = '11112222@ba'
strip3 ='    112344'
print(strip3.lstrip()) #112344 默认删除控股
print(strip3.lstrip('1'))# 没有 返回原本式子
print(strip3.lstrip('4'))#     112344 原样输出
print(strip1.lstrip('!')) # 删除所有相同
print( 'www.example.com'.lstrip('cmowz.'))
print('11223344'.lstrip('21s'))#3344 没有的就忽略 有的就删除 和

  • strip讲解
 strip(...)
 |      S.strip([chars]) -> str
 |      # 删除字符串头尾的指定字符(默认是空白字符:/n, /r, /t, ' '))
 |      Return a copy of the string S with leading and trailing whitespace removed.
 #返回一个被清除完的S的副本,
 |      If chars is given and not None, remove characters in chars instead.
 #如果字符串没有或者是默认,是删除空白,或者返回原本的
#strip
print(' \t\v\b\nabcd1234 '.strip()) #abcd1234

字符串内置函数–maketrans()/translate

  • 这里是定义的静态方法,python3.4之后没有这个方法
  • maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。 其实就是对应的调用关系,现在是用bytearray.maketrans()、bytes.maketrans()、str.maketrans() 。
  • 简单来说,定义x,定义y,x–>y ,y会替代x。 x和y的长度是要相等的,z将会被映射为None即会删除该字符,如果z中字符与x中字符重复,在结果中还是会删除,也就是只要z有,就一定会删除。z一定要是字符串
  • 一般和tanslate 搭配使用
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))
  • 可以直接吧x,y写成 字典的形式,也就是如果是一个参数,就必须是字典的形式 ,会先将齐转换为ACSII码,后用translate进行解析
d = {'a':'1','b':'2','c':'3','d':'4','e':'5','s':'6'}
trantab = str.maketrans(d) # 先转换ASCII码 然后translate再翻译
print(trantab) # {97: '1', 98: '2', 99: '3', 100: '4', 101: '5', 115: '6'}
st='just do it'
print(st.translate(trantab))
#ju6t 4o it
  • 含有 x y z 三个参数
x = 'abcdefs'
y = '1234567'
z = 'ot'  # z中是会被删除的内容 无论如何都会被删除
st = 'just do it'
trantab = st.maketrans(x,y,z)
print(trantab) #9个
# {97: 49, 98: 50, 99: 51, 100: 52, 101: 53, 102: 54, 115: 55, 111: None, 116: None}
print(st.translate(trantab))
#ju7 4 i # ot 被删除
  • help 翻译
 Static methods defined here:
 #Python3.4 已经没有 string.maketrans() 了,取而代之的是内建函数: bytearray.maketrans()、bytes.maketrans()、str.maketrans() 。
# 这里是定义的静态方法
 |  
 |  maketrans(x, y=None, z=None, /)
 
 |      Return a translation table usable for str.translate(). # 返回一个字符映射 
 |      
 |      If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None.
 # 如果只有一个参数,那么应该是字典地图编码 (整型或者是字符串) 如果只有一个参数,那么它必须是一个将Unicode序数(整数)或字符映射到Unicode序数、字符串或None的字典。
 |      Character keys will be then converted to ordinals.
 #字符键会转化成序列
 |      If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the  character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.#如果参数是两个,那么字符串的长度要相等,并且是意义对应的转换关系,如果有第三个参数,那么一定就是字符串类型,

  • translate 和masktrans 搭配使用,进行逆操作。上诉例子为准。

字符串内置函数–max()/min()

  • 字符串 以ASCII码进行比较
  • 能够使用这个的类型有很多,但是要在同一个数据类型下进行比较
  • max() 返回字符串中的最大的,min()返回字符串中最小的
#max
print(max('111'))#1
print(max('123'))#3
print(max('abc'))#c 98 99 100
print(max('Aa12'))#a 

字符串内置函数–replace()

  • str.replace(old,new[,count]) 使用新的字符串来替代旧的字符串,如果第三个参数定义则表示不超过替换次数count。
  • 返回的是字符串类型
  • 替换的内容需要是字符串类型,old new 需要是字符串类型
  • 不会改变原始的数据,因为输出的是变换后的副本,
  • 如果需要替换的内容没有 就原样输出
  • count的次数是替换的次数,内容大于、小于、等于次数时候,停止替换,
  • 类似遍历 替换 变成了集成的方法
replace(...)
 |      S.replace(old, new[, count]) -> str
 |      # 新旧替换,并有最多替换次数,返回字符串
 |      Return a copy of S with all occurrences of substring old replaced by new.  If the optional argument count is given, only the first count occurrences are replaced.
 # 返回一个s的副本,当old被new替换的时候,如果操作数count给定,那么只替换第一次出现的count的参数,意思是count可以定义多个,但是只执行第一个count
 |  
# repalce
print('replace')
r1 = 'this is a is sentence is wa'
r2 = 'this aaa hhh yy'
print(r1.replace('is','was')) #thwas was a was sentence was wa
print(r1) #this is a is sentence is wa
print(r1.replace('is','not int'))
print(r2.replace('v','1')) #this aaa hhh yy
print(r1.replace('is','count',))

字符串内置函数–split()/rsplit()

  • str.split() 通过指定分割符对字符串进行切片,如果第二个参数有指定值,则分割为num+1 个字符串
  • str.split(str="",num=string.count(str));str分割符,默认为所有的空字符\t \n \r 空格 ,num分割次数,空格优先分割
  • 返回一个字符串为内容的列表形式 [‘1’,‘2’…]
  • 如果分隔符的内容不存在,会将整个字符串作为列表list 返回,分隔符会被删除
  • num 是定义分割次数,分割n次,输出n+1个字符串;内容小于num,会以内容为最大次数,num如果定义错误,也就是为负数、超出都以最大次数划分。
  • 可以定义以什么分割
  • rsplit如果未指定 “num”,则此方法将返回与 split() 方法相同的结果。rsplit 从右往左,split 从左到右
split(...)
 |      S.split(sep=None, maxsplit=-1) -> list of strings
 |      
 |      Return a list of the words in S, using sep as the
delimiter string.  If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
#返回一个单词列表在S,使用sep作为
#分隔符的字符串。如果给定了maxsplit,则最多执行maxsplit分割。如果没有指定sep或sep为空,则任何空白字符串都是分隔符,空字符串将从结果中删除。  其实就是空白字符作为默认值
 rsplit(...)
 |      S.rsplit(sep=None, maxsplit=-1) -> list of strings
 |      
 |      Return a list of the words in S, using sep as the
 |      delimiter string, starting at the end of the string and # 从后到前
 |      working to the front.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified, any whitespace string
 |      is a separator.
# split
print('split')
spt = 'This is string example ... wow !!'
print(spt.split()) # ['This', 'is', 'string', 'example', '...', 'wow', '!!']
sptt = 'Thisis\tdestring\t'
print(sptt.split()) #['Thisis', 'destring'] 空格优先
print(spt.split('ha')) #['This is string example ... wow !!']
print(spt.split('is'))#['Th', ' ', ' string example ... wow !!']
print(spt.split('is',1)) #['Th', ' is string example ... wow !!']
print(spt.split('is',3))
print('1')
print(spt.split('is',-5))#['Th', ' ', ' string example ... wow !!']

# 两者区别
print('ais bis c ishashhishwerisihjd'.split('is',1))
print('ais bis c ishashhishwerisihjd'.rsplit('is',1))
#['a', ' bis c ishashhishwerisihjd']
#['ais bis c ishashhishwer', 'ihjd']

字符串内置函数–splitlines()

  • str.splitlines([Treu/False]) 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符,默认False,注意\n\r是分为两个,这样写会出''空字符串
 splitlines(...)
 |      S.splitlines([keepends]) -> list of strings
 |      #  返回一个列表list 里面都是字符串类型
 |      Return a list of the lines in S, breaking at line boundaries. #返回行列表,打破行边界
 |      Line breaks are not included in the resulting list unless keepend is given and true.
 |  # 如果keepends -=True 就会保留换行符 不然不保留,默认不保留
# splitlinse
print('splitlines')
print('abc\nthdhh\rhjk\n\rajd\r\n'.splitlines())
#['abc', 'thdhh', 'hjk', '', 'ajd'] # 空字符串
print('abc\nthdhh\rhjk\n\rajd\r\n'.splitlines(True))
#['abc\n', 'thdhh\r', 'hjk\n', '\r', 'ajd\r\n']

字符串内置函数—partition/rpartition

  • str.partition(sep) 如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串;不包含分隔符就返回Str和两个空字符串。
  • 只会分隔一个,也就是只会返回三个答案,并且只有一个参数
  • str.rpartition 从右到左进行查询,输出还是按照顺序输出的。
  • 返回的是元祖的形式啊(head, sep, tail),head 是安装顺序输出的,
 partition(...)
 |      S.partition(sep) -> (head, sep, tail)
 |      # 根据指定的分隔符 将字符串进行分割,
 |      Search for the separator sep in S, and return the part before it,# 字符串中搜索sep,把sep前的分割,sep,sep后面
 |      the separator itself, and the part after it. 
  If the separator is not found, return S and two empty strings. # 如果sep没有找到,返回s和两个空字符串。
 |  
 |  rpartition(...)
 |      S.rpartition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, starting at the end of S, and return
 |      the part before it, the separator itself, and the part after it.  If the
 |      separator is not found, return two empty strings and S.
 |  
#partition
print('partition')
print('ab.cim./sd'.partition('.'))#分割一个 #('ab', '.', 'cim./sd')
print('ab.cim..sd'.partition('@')) # ('ab.cim..sd', '', '')
print('ab.cim..,sd'.rpartition('.'))#('ab.cim.', '.', ',sd')

字符串内置函数—isprintable() 补

  • str.isprintable() 返回的是bool。判断字符串是否都是可打印字符,或者字符串为空。
  • 制表符、换行符都是不能打印的
    - 什么是可以打印的 什么是不能打印的 不知道 需要补

Unicode字符集中“Other” “Separator”类别的字符为不可打印的字符(但不包括ASCII码中的空格(0x20))。可用于判断转义字符。
ASCII码中第0~32号及第127号是控制字符;第33~126号是可打印字符,其中第48~57号为0~9十个阿拉伯数字;65~90号为26个大写英文字母,97~122号为26个小写英文字母。

#!/usr/bin/python3
 
print('oiuas\tdfkj'.isprintable()) #制表符 false
print('oiuas\ndfkj'.isprintable()) #换行符 false
 
print('oiu.123'.isprintable()) #true
print('oiu 123'.isprintable()) #true
print('~'.isprintable())#true
print(''.isprintable())#true

字符串内置函数—isidentifier()

  • 判断是否是有效的标识符,可以判断变量名是否合法,返回bool值,
  • 判断是否是有效标识符,是则返回true,可以使用keyword来验证。
  • 如果字符串仅包含字母数字字母(a-z)和(0-9)或下划线(_),则该字符串被视为有效标识符。有效的标识符不能以数字开头或包含任何空格。
  • 不能空字符串
 |  isidentifier(...)
 |      S.isidentifier() -> bool
 |      
 |      Return True if S is a valid identifier according
 |      to the language definition.
 |      # 有效标识符返回true
 |      Use keyword.iskeyword() to test for reserved identifiers #使用keyword.iskeyword 去测试
 |      such as "def" and "class".
 |
print( "if".isidentifier() ) # true
print( "def".isidentifier() ) #true
print( "class".isidentifier() ) #true
print( "_a".isidentifier() )#true
print( "中国123a".isidentifier() )#true
print( "123".isidentifier() ) #false
print( "3a".isidentifier() )#false
print( "".isidentifier() )#false

字符串内置函数—format()

  • str.format() 格式化字符串,参数不受限制,位置可以不按顺序
  • 按顺序对应获取数据
  • 按下标对应获取数据 从0开始
  • 按变量名获取数据
  • 如果数据是字典,需要**dist名获取
  • 如果数据是数组列表,需要列表[][]这样获取
  • 数据多余填充数,则忽略数据 ;填充数据超过数据会报错IndexError: tuple index out of range 元组范围超出
  • 无法手动的获取到自动获取 所以过少不行,也就是自动获取和定义获取不能一起用
format(...) method of builtins.str instance
    S.format(*args, **kwargs) -> str
    
    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').


#format
print('format')
print('{},{}'.format('1',2))# 1,2  不考虑形式
print('{0},{1}'.format('s1',set('123')))#s1,{'3','1','2'}
# 指定位置 下标从0开始 format里的数据没有限制
# 也可以重复调用,没有调用就对应给予
#  不够 或过多怎么办  过多忽略
print('{1}{1}{0}'.format('1',2,set('123')),)#221
#print('{1}{1}{0}{}'.format('1',2,set('123')))
#ValueError: cannot switch from manual field specification to automatic field numbering
# 无法手动的获取到自动获取 所以过少不行
# 指定key
print('{test1}{test2}'.format(test1='hh',test2='?')) #hh?
#字典设置参数
site = {"name":"ysy","age":12}
#print('{name}{age}'.format(site)) 这样会以为site是key
print('{name}{age}'.format(**site))#ysy12
# 字典用法

# 列表索引
list1 = ['hello','world']
list2 = ['hi','hah']
#print({0[1]},{1[1]}'.format(list1,list2))
# #TypeError: 'int' object is not subscriptable 要字符串类型
print('{0[1]},{1[1]}'.format(list1,list2))#world,hah

字符串内置函数—format_map

单独开章 后补链接

 |  
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |      
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').

help(str) 补’__’ 不懂二者的区别

包含str的定义,也包含它所有具有的方法
(本英语渣又要进行翻译了)

class str(object)  # str(object) 参数是一个对象 随手百度了一下 object好像是继承的概念,还没深入,和js不知道是否一样,暂定
 |  str(object='') -> str  # 我猜 str(object=‘’) ->str object 是继承str的意思吗? 默认str()的时候会输出一个空字符串 ''
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str 
 	# str(字节或者是进制的意思吧) encoding是可选参数:编码的意思,errors也是可选
 |  
 |  Create a new string object from the given object.
 	#从给定的对象中获得一个新的字符对象
	 If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler.
	# 如果指定了编码或错误,则对象必须公开一个数据缓冲区,该缓冲区将使用给定的编码和错误处理程序进行解码。我觉得这里说的是二进制
 |  Otherwise, returns the result of object.__str__() (if defined)or repr(object).
 # 否则 返回 object.__str()__的结果,或者是repr(object) 如果定义了的话
 |  
 |  encoding defaults to sys.getdefaultencoding().
 	# 编码默认是 sys.getdefaultencoding()
 |  errors defaults to 'strict'.
 |  #错误默认是 strict
 |  Methods defined here: #str的方法
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(...)
 |      S.__format__(format_spec) -> str
 |      
 |      Return a formatted version of S as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __str__(self, /)
 |      Return str(self).
  
 |  casefold(...)
 |      S.casefold() -> str
 |      
 |      Return a version of S suitable for caseless comparisons.
 

 


发布了35 篇原创文章 · 获赞 2 · 访问量 9809

猜你喜欢

转载自blog.csdn.net/qq_39532595/article/details/104439415
今日推荐