capitalize(...)| S.capitalize()->str#输出是一个字符串|| Return a capitalized version of S, i.e. make thefirst character have upper case and the rest lower case.#返回一个首字母大写的字符串,即让第一个字母大写,其余字母小写
首字符会转换成大写,其余的都会转换成小写,针对的就是第一个字符而言
首字符如果是非字母,则保持不变,并且其余的都会变成小写
# capitalize 如何查 数据类型的方法print('helloWorld111'.capitalize())# Helloworld111print('Hello World 123'.capitalize())# 不是单词第一个大写哦print('1HelloWowW'.capitalize())#1hellowoww 起始是数字也不行 就是默认第一位。print('~!heEW'.capitalize())
参数至少为一个,最多为两个,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)# fillcharprint('111111111111111111111111')#24print('hello'.center(24))print('hello'.center(3,'1'))# helloprint('hello'.center(10,'-'))print('hello'.center(10,'*'))#print('hello'.center(10,'ss')) #The fill character must be exactly one character long
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 asinslice notation.#可选参数start end 被解释为切片符号,也就是起始和结束|
endswith(...)# 字符串字段以这个结尾| S.endswith(suffix[, start[, end]])->bool|# s.endswith('可以理解为内容',statr,end)| Return Trueif 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('!'))# trueprint(str3.endswith('!!'))#trueprint(str3.endswith('!!!'))#trueprint(str3.endswith(('!!!!!')))#falseprint(str3.endswith('a'))#falseprint(str3.endswith('a',0))#falseprint(str3.endswith('a',0,1))#trueprint(str3.endswith('c',1,3))#true end取不到#print(str3.endswith((1)))# 元组
strtup ='123abcd123!!!'#print(strtup.endswith(((1,2,3)))) typeerrorprint(strtup.endswith(('1','2','3')))#true 必须 字符串# 顺序不一样怎么办print(strtup.endswith(('2','1','3','!')))#trueprint(strtup.endswith(('@','!')))#falseprint(strtup.endswith(('!','1','2','!','3')))#true?print(strtup.endswith(('!','1','2','!','3'),0,-4))#true# 自助排列??print('?')print(strtup.endswith(('!','2','!'),0,-4))#true
expandtabs(...)| S.expandtabs(tabsize=8)->str# 返回字符串|| Return a copy of S where all tab characters are expanded using spaces.# 将字符串中的制表符号 \t 全部变成 控股| If tabsize isnot 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))# 默认是8print(extabst.expandtabs(9))print(extabst.expandtabs(12))print(extabst.expandtabs(16))'''
abcdefghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyz
'''
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 asinslice 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 intprint(strfind.find('ab'))#0print(strfind.find('ac'))#-1 不能组合print(strfind.find('ab',-6,-1))#12print(strfind.find('ab',-1,-6))#-1 不能逆序print(strfind.find('!',-1,-6))# 这样是不存在 start end不合法#输出的位置都是正序的
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 asinslice notation.|| Return -1 on failure.# rfind 查找最后一个出现的位置
rdn ='abcdedd!!hh111@@!!'print(rdn.rfind('1'))#13print(rdn.rfind('@',8,-1))#15print(rdn.rfind('@',16,-1))#-1print(rdn.rfind('@',-3,-1))#15print(rdn.rfind('@',-1,-3))#-1
功能与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 asinslice notation.|| Raises ValueError when the substring isnot found.# ValueError
strindex ='abcdefg111@1aba!!!'print(strindex.index('a'))#0#print(strfind.find(1) ) must be str.not intprint(strindex.index('ab'))#0#print(strindex.index('ac'))#-1 不能组合ValueError: substring not foundprint(strindex.index('ab',-6,-1))#12#print(strindex.index('ab',-1,-6))#-1 不能逆序#print(strindex.index('!',-1,-6)) # 这样是不存在 start end不合法#输出的位置都是正序
isalnum(...)| S.isalnum()->bool|# 判断字符串是否由 字母和数字组成 返回的是bool布尔值| Return Trueifall characters in S are alphanumeric|and there is at least one character in S,False otherwise.# s中至少有一个字符,|print(''.isalnum())# falseprint('\t'.isalnum())#falseprint('\000'.isalnum())#falseprint('00\\'.isalnum())#falseprint('和'.isalnum())#trueprint('HHhh'.isalnum())#trueprint('H12h@'.isalnum())#falseprint('0.0'.isalnum())#falseprint('\x16'.isalnum())#false#print(('1','2').isalnum()) 元组等不具有这个方法
isalpha(...)| S.isalpha()->bool|# 检测字符串是否只由字母和文字组成 bool 类型| Return Trueifall characters in S are alphabetic|and there is at least one character in S,False otherwise.# isalphaprint('isalpha')print(''.isalpha())#falseprint('哈'.isalpha())#trueprint('1'.isalpha())#falseprint('hh'.isalpha())#trueprint('11hh'.isalpha())#falseprint('11哈哈'.isalpha())#falseprint('@@'.isalpha())#falseprint('\n'.isalpha())#false
字符串内置函数–isdigital() 是否只有数字构成
str.isdigital() 检测字符串是否只有数字组成,并且至少要有一个字符
isdigit(...)| S.isdigit()->bool|# 判断是否只有字符串组成| Return Trueifall characters in S are digits|and there is at least one character in S,False otherwise.|# 至少要有一个字符#isdigitprint('isdigit')print(''.isdigit())#falseprint('False'.isdigit())#falseprint('hh'.isdigit())#falsepprint('11'.isdigit())#trueprint('11tt'.isdigit())#falseprint('@'.isdigit())#falseprint('哈哈'.isdigit())#false
字符串内置函数–islower()/isupper() 含有字母但只有小写/大写
str.islower() 至少有一个字符,并且都是小写
这里的意思是,无论str字符串中包含了什么数据内容,只要是包含的字母,并且都是小写就会输出true
如果str的内容都是非小写字符,或者没有小写字符,都是返回false
str.isupper() 与islower()相反,只要含有字母,并且都是大写就会返回True。
islower(...)| S.islower()->bool|# 是否由小写字母组成 返回bool值| Return Trueifall cased characters in S are lowercase and there is at least one cased character in S,False otherwise.#字符串中至少有一个字符串,并且全部都是小写,返true,否则false|# islowerprint('islower')print(''.islower())#falseprint('1'.islower())#falseprint('A'.islower())#falseprint('a'.islower())#trueprint('aA'.islower())#falseprint('!'.islower())#falseprint('11a'.islower())#trueprint('哈哈'.islower())#falseprint('哈哈11aaa'.islower())#trueprint('@@1a'.islower())#true
字符串内置函数–isnumeric() 是否有数字组成
str.isnumeric() 方法检测字符串是否只由数字组成,数字可以是: Unicode 数字,全角数字(双字节),罗马数字(例子:VI)*,汉字数字(例子:二),但是不识别字节。 指数类似 ² 与分数类似 ½ 也属于数字。
'bytes' object has no attribute 'isnumerice' 字节不行哦
isnumeric(...)| S.isnumeric()->bool|# isnumeric 返回bool | Return Trueif 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 0print(a.isnumeric())b ="\u00B2"#unicode for ²print(b.isnumeric())c ="10km2"print(c.isnumeric())print('a'.isnumeric())#falseprint('1'.isnumeric())#true#print(b'1'.isnumerice()) noprint('\u00B23455'.isnumeric())#trueprint('四'.isnumeric())#trueprint('叁'.isnumeric())#trueprint('三df'.isnumeric())#false
isdecimal(...)| S.isdecimal()->bool|| Return Trueif there are only decimal characters in S,False otherwise.print('12'.isdecimal())#trueprint('a'.isdecimal())#falseprint(u'a123'.isdecimal())#False
isspace(...)| S.isspace()->bool|# | Return Trueifall characters in S are whitespace|and there is at least one character in S,False otherwise.# 字符串中是否只包含空格 是true 不是false|print('space')print(''.isspace())#falseprint('\r'.isspace())#trueprint('\t'.isspace())#trueprint('1\t'.isspace())#falseprint('\n'.isspace())#trueprint(' '.isspace())#trueprint('1\b'.isspace())#falseprint(' 1\b'.isspace())#false
可以有其他字母,并且是空格隔开 是一个整体,无论里面有几个单词,都只能首字母大写,不然输出False,HelloHi 这种就算一个单词,每一个单词都需要大写Hell hi 这样会返回False,以非字母的后一个字符是否为大写为判断依据
前面可以有其他的字符,只要第一个遇到的字母是大写,其余是小写的字符串,就true
缩写的均为大写,返回的也是False,例如SOS
不会自动转换为首字母大写的形式
istitle(...)| S.istitle()->bool# 判断单词首字母大写 其他为小写 返回bool型#并且至少要有一个字符|| Return Trueif 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.# istitleprint(''.istitle())#falseprint('1F'.istitle())#Trueprint('FatherHi'.istitle())#Falseprint('1@Father'.istitle())#trueprint('Hi hllo'.istitle())#Falseprint('SOS'.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,即单词以标题大小写字符开头,所有其余的大小写字符都是小写的。#titleprint('Ti hb1H!178js)-2hk 哈哈hjau'.title())#Ti Hb1H!178Js)-2Hk 哈哈Hjau
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-dprint(s2.join(seq))#h1e1l1l1o1 1w1o1r1l1dprint(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()不是字符串类的方法 需要区分后补
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.ljustprint('hello'.ljust(10,'-'))#hello-----print(s3.ljust(30,'0'))#---000000000000000000000000000#print('hello'.ljust(30,'--'))
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.#返回转换为小写字符串的副本# lowerprint('lower')
slow ='H1H2hhh@1}}!!'
slow2 =set('123hHHHH')print(slow.lower())#h1h2hhh@1}}!!#print(slow2.lower())#'set' object has no attribute 'lower'
| swapcase(...)| S.swapcase()->str| Return a copy of S with uppercase characters converted to lowercase and vice versa.# 大小写转换 并且是给一个副本# swapcaseprint('abcABC!!!###%%%'.swapcase())#ABCabc!!!###%%%print(''.swapcase())#''print('哈哈'.swapcase())#哈哈
lstrip(...)| S.lstrip([chars])->str3 返回字符串| Return a copy of the string S with leading whitespace removed.# 返回删除了空格的字符串副本,所以就是不影响原本的数据| If chars is given andnotNone, remove characters in chars instead.# 如果提供了字符而不是没有字符,则删除字符中的字符#lstripprint('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 andnotNone, remove characters in chars instead.#如果字符串没有或者是默认,是删除空白,或者返回原本的#stripprint(' \t\v\b\nabcd1234 '.strip())#abcd1234
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 forstr.translate().# 返回一个字符映射 || If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers)or characters to Unicode ordinals, strings orNone.# 如果只有一个参数,那么应该是字典地图编码 (整型或者是字符串) 如果只有一个参数,那么它必须是一个将Unicode序数(整数)或字符映射到Unicode序数、字符串或None的字典。| Character keys will be then converted to ordinals.#字符键会转化成序列| If there are two arguments, they must be strings of equal length,andin 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 Nonein the result.#如果参数是两个,那么字符串的长度要相等,并且是意义对应的转换关系,如果有第三个参数,那么一定就是字符串类型,
replace(...)| S.replace(old, new[, count])->str|# 新旧替换,并有最多替换次数,返回字符串| Return a copy of S withall 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|# repalceprint('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 waprint(r1)#this is a is sentence is waprint(r1.replace('is','not int'))print(r2.replace('v','1'))#this aaa hhh yyprint(r1.replace('is','count',))
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 isnot specified orisNone,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 isnot specified,any whitespace string|is a separator.# splitprint('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(...)| 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 就会保留换行符 不然不保留,默认不保留# splitlinseprint('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(...)| S.partition(sep)->(head, sep, tail)|# 根据指定的分隔符 将字符串进行分割,| Search for the separator sep in S,andreturn the part before it,# 字符串中搜索sep,把sep前的分割,sep,sep后面| the separator itself,and the part after it. If the separator isnot 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,andreturn| the part before it, the separator itself,and the part after it. If the| separator isnot found,return two empty strings and S.|#partitionprint('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')
| isidentifier(...)| S.isidentifier()->bool|| Return Trueif 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())# trueprint("def".isidentifier())#trueprint("class".isidentifier())#trueprint("_a".isidentifier())#trueprint("中国123a".isidentifier())#trueprint("123".isidentifier())#falseprint("3a".isidentifier())#falseprint("".isidentifier())#false
字符串内置函数—format()
str.format() 格式化字符串,参数不受限制,位置可以不按顺序
按顺序对应获取数据
按下标对应获取数据 从0开始
按变量名获取数据
如果数据是字典,需要**dist名获取
如果数据是数组列表,需要列表[][]这样获取
数据多余填充数,则忽略数据 ;填充数据超过数据会报错IndexError: tuple index out of range 元组范围超出
无法手动的获取到自动获取 所以过少不行,也就是自动获取和定义获取不能一起用
format(...) method of builtins.str instanceS.format(*args,**kwargs)->strReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{'and'}').#formatprint('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# 无法手动的获取到自动获取 所以过少不行# 指定keyprint('{test1}{test2}'.format(test1='hh',test2='?'))#hh?#字典设置参数
site ={"name":"ysy","age":12}#print('{name}{age}'.format(site)) 这样会以为site是keyprint('{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的定义,也包含它所有具有的方法 (本英语渣又要进行翻译了)
classstr(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 objectfrom 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)orrepr(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 andreturn 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,inbytes|| __str__(self,/)| Return str(self).| casefold(...)| S.casefold()->str|| Return a version of S suitable for caseless comparisons.