欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

怎么使用Python中的字符串

本篇內(nèi)容介紹了“怎么使用Python中的字符串”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

創(chuàng)新互聯(lián)主營金堂縣網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,app軟件開發(fā)公司,金堂縣h5重慶小程序開發(fā)搭建,金堂縣網(wǎng)站營銷推廣歡迎金堂縣等地區(qū)企業(yè)咨詢

字符串的定義

python定義字符、字符串沒有java那樣的嚴(yán)格,不管是單引號、雙引號、甚至是三個單引號和雙引號都可以用來定義字符(串),只要成對出現(xiàn)即可。比如:

# 單個字符 a='a' # 使用單引號定義字符串 name='Uranus' # 使用雙引號定義字符串 code = "Hello World ..." # 既然說到了string,怎么能不點開源碼看看呢? class str(object):     """     str(object='') -> str     str(bytes_or_buffer[, encoding[, errors]]) -> str     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).     encoding defaults to sys.getdefaultencoding().     errors defaults to 'strict'.     """

雖然這些不是主要說的,但還是簡單提下,三個單引號或者雙引號,主要是用來作為文檔注釋的,請不要拿來定義字符串(雖然這樣并不會出現(xiàn)語法錯誤)。

今天主要說下關(guān)于打段的字符串應(yīng)該如何定義,PEP8有規(guī)定,一行代碼的長度請勿超過120個字符。那么如果遇到這種情況,該怎么辦?

# 不推薦的使用方式: line = """ 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. """ # 或者這樣 line = "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." # 更好的實現(xiàn)方式: line = ("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."         )

字符串中.is()的用法

.is*(), 既然是is,那么它返回的結(jié)果只有兩種,True or False

先來對比一下數(shù)字:

isdigit() True: Unicode數(shù)字,byte數(shù)字(單字節(jié)),全角數(shù)字(雙字節(jié)),羅馬數(shù)字 False: 漢字?jǐn)?shù)字 Error: 無  isdecimal() True: Unicode數(shù)字,全角數(shù)字(雙字節(jié)) False: 羅馬數(shù)字,漢字?jǐn)?shù)字 Error: byte數(shù)字(單字節(jié))  isnumeric() True: Unicode數(shù)字,全角數(shù)字(雙字節(jié)),羅馬數(shù)字,漢字?jǐn)?shù)字 False: 無 Error: byte數(shù)字(單字節(jié))

總結(jié)幾個偏門知識點:

a='①②③④⑤' isdigit()、isnumeric() 為True isdecimal()為False b='一壹' isnumeric()會認(rèn)為是True的哦!

再來看一個等式:

isalnum() = isdigit() + isalpha() + isspace() isdigit()表示字符串內(nèi)全部為數(shù)字 isalpha()表示字符串內(nèi)全部為字符 isspace()表示字符串有一個或多個空格組成 isalnum()表示字符串內(nèi)全部為數(shù)字和字符
a='12345' b='①②③④⑤' c='abc123'  print(a.isdigit()) # True print(b.isalpha()) # True print(c.isalnum()) # True

針對字符串大小寫的方法:

.isupper() 字符串全部由大寫組成 .islower() 字符串全部由小寫組成 .istitle() 字符串形式為駝峰命名,eg:"Hello World"

以上這些用法去掉is,則變?yōu)榱藢?yīng)的字符串轉(zhuǎn)發(fā)方法。學(xué)一套會兩套,買一送一….

最后說一個不帶.的is* --- isinstance(obj,type)。

判斷一個object是什么類型… type可選類型為:int,float,bool,complex,str,bytes,unicode,list,dict,set,tuple 并且type可以為一個原組:isinstance(obj, (str, int))

判斷字符串中的內(nèi)容

.*with() starts ends 不僅支持開頭結(jié)尾的匹配,還支持start和end兩個參數(shù)來動態(tài)定義字符串的index位置。

long_string = "To live is to learn,to learn is to better live" long_string.startswith('To') long_string.startswith('li', 3, 5) long_string.endswith('live') long_string.endswith('live', 0, 7)

同樣支持start、end來判斷字符串的還有 .find()、.rfind()和 .index()、.rindex()

這兩類字符串尋址方法均支持從左到右、從右至左兩種尋址方式,不同的是:

find在未找到時,返回-1,而index在未找到時,會拋出ValueError的異常…

long_string.index('live') # 3 long_string.rindex('live') # 42

字符串的內(nèi)容變更

狹義來說使用,字符串的替換使用.replace()即可,那為什么還要單獨說呢?因為它有一個可選參數(shù)count。

long_string = "To live is to learn,to learn is to better live" long_string.count('live') # 2 long_string.replace('live','Live',1) output: 'To Live is to learn,to learn is to better live' # 可以看到,第二個live并未進行替換

剛才說了狹義,那么廣義呢?

1.(l/r)strip()

將字符串左、右、兩端的特定字符過濾掉,默認(rèn)為空格…

strip()要注意的地方是,strip('TolLive') 中的字符并非完整匹配,而是針對每一個字符進行匹配,說起來混,直接上例子:

long_string = "To live is to learn,to learn is to better live" long_string.strip('TolLive') 's to learn,to learn is to better'

2.字符串切片

字符串的切片分為long_string[start:end;step]  start、end區(qū)間為左閉右開…這個網(wǎng)上說的太多了,再拉出來詳細(xì)講就要挨打了…

(l/r)just(width,[fillchar])、center(width, [fillchar])、zfill(width)

這些均為填充固定長度的字符,默認(rèn)使用空格(zfill為左補0,z是zero的意思…),看意思就明白了,不用多講了….

字符串格式化輸出

本來fill和center等可以放在這里,但是他們使用頻率和重量級不夠格,就丟在上面了。

Python格式化輸出分為兩類,那是在pyton2的時代,即 % 和 format。這兩種網(wǎng)上的資料太多了,說的太多顯得沒逼格…

但,還是要簡單說說其中特殊的地方。

1.% 格式化輸出:

  • 如何在%的格式輸出中,輸出用來看做標(biāo)記為的%符號呢?使用兩個百分號(%%)

  • %(-)(width) width為設(shè)置長度,默認(rèn)左填充空格,添加-號為右填充

  • .width代表字符串截斷,保留多少長度的字符串

  • type %s字符串 %d十進制整數(shù) %f小數(shù) …

  • 多個參數(shù)是,后面的參數(shù)需要使用括號包裹起來

'姓名:%-5s 年齡:%4d 愛好: %.8s' % ('王大錘',30,'python、Java') output: '姓名:王大錘   年齡:  30 愛好:python、J'

2.format格式輸出:

format在python3開始官方就表示為替換%的輸出方式,之所以還保留著%,主要是為了兼容性考慮…

  • 對比%,format使用花括號{}表示變量

  • < > ^ 代表了format的對齊方式 

'{:-^40s}'.format('華麗的分割線') output: '-----------------華麗的分割線-----------------'

3.f-string

Python3.6的版本更新時,新增了f-string,英文好的可以去看官方解釋PEP 498 -- Literal String  Interpolation 。

f-string是字符串引號前以f/F開頭,并使用{}標(biāo)注替換位置的使用形式。

之所以官方推出f-string,主要是因為它的更高的性能、更強的功能。例子走起:

name = 'Uranus' f'Hello,{name}' f'Hello,{name.lower()}' f'Hello,{name:^10s}' f'Hello,{(lambda x: x*2) (name)}'  output: 'Hello,Uranus' 'Hello,uranus' 'Hello,  Uranus  ' 'Hello,UranusUranus'

“怎么使用Python中的字符串”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

當(dāng)前題目:怎么使用Python中的字符串
標(biāo)題鏈接:http://chinadenli.net/article8/geoeip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版外貿(mào)建站App設(shè)計網(wǎng)站設(shè)計Google網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)