日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2024/3/24 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 来自python的【str字符串内置函数】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

字符串內置函數–capitalize 遇見非字符串后,下一個字符大寫

  • str.capitalize():將字符串轉換成大寫,其他字母變成小寫

  • capitalize 含義

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())# 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)) ''' abcdefghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde fghijklmnopqrstuvwxyzabcde 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)*,漢字數字(例子:二),但是不識別字節。
    指數類似 2 與分數類似 ? 也屬于數字。
  • '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 = '23455' s = '\u00B23455' print(s.isnumeric()) # s = '?' s = '\u00BD' print(s.isnumeric())a = "\u0030" #unicode for 0 print(a.isnumeric())b = "\u00B2" #unicode for 2 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() 以0填充至寬度

  • 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/python3print('oiuas\tdfkj'.isprintable()) #制表符 false print('oiuas\ndfkj'.isprintable()) #換行符 falseprint('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 instanceS.format(*args, **kwargs) -> strReturn 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.

總結




總結

以上是生活随笔為你收集整理的来自python的【str字符串内置函数】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。