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
'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 = '23455'
s ='\u00B23455'print(s.isnumeric())# s = '?'
s ='\u00BD'print(s.isnumeric())a ="\u0030"#unicode for 0print(a.isnumeric())b ="\u00B2"#unicode for 2print(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.