Python入門學(xué)習(xí)之字符串與比較運算符
Python字符串
字符串或串(String)是由數(shù)字、字母、下劃線組成的一串字符。
一般記為 :
s="a1a2···an"(n>=0)
它是編程語言中表示文本的數(shù)據(jù)類型。
python的字串列表有2種取值順序:
- 從左到右索引默認0開始的,最大范圍是字符串長度少1
- 從右到左索引默認-1開始的,最大范圍是字符串開頭
- 如果你的實要取得一段子串的話,可以用到變量[頭下標:尾下標],就可以截取相應(yīng)的字符串,其中下標是從0開始算起,可以是正數(shù)或負數(shù),下標可以為空表示取到頭或尾。
比如:
s = 'ilovepython'
s[1:5]的結(jié)果是love。
當(dāng)使用以冒號分隔的字符串,python返回一個新的對象,結(jié)果包含了以這對偏移標識的連續(xù)的內(nèi)容,左邊的開始是包含了下邊界。
上面的結(jié)果包含了s[1]的值l,而取到的最大范圍不包括上邊界,就是s[5]的值p。
加號(+)是字符串連接運算符,星號(*)是重復(fù)操作。如下實例:
#!/usr/bin/python # -*- coding: UTF-8 -*- str = 'Hello World!' print str # 輸出完整字符串 print str[0] # 輸出字符串中的第一個字符 print str[2:5] # 輸出字符串中第三個至第五個之間的字符串 print str[2:] # 輸出從第三個字符開始的字符串 print str * 2 # 輸出字符串兩次 print str + "TEST" # 輸出連接的字符串
以上實例輸出結(jié)果:
Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST
Python比較運算符
以下假設(shè)變量a為10,變量b為20:
以下實例演示了Python所有比較運算符的操作:
#!/usr/bin/python a = 21 b = 10 c = 0 if ( a == b ): print "Line 1 - a is equal to b" else: print "Line 1 - a is not equal to b" if ( a != b ): print "Line 2 - a is not equal to b" else: print "Line 2 - a is equal to b" if ( a <> b ): print "Line 3 - a is not equal to b" else: print "Line 3 - a is equal to b" if ( a < b ): print "Line 4 - a is less than b" else: print "Line 4 - a is not less than b" if ( a > b ): print "Line 5 - a is greater than b" else: print "Line 5 - a is not greater than b" a = 5; b = 20; if ( a <= b ): print "Line 6 - a is either less than or equal to b" else: print "Line 6 - a is neither less than nor equal to b" if ( b >= a ): print "Line 7 - b is either greater than or equal to b" else: print "Line 7 - b is neither greater than nor equal to b"
以上實例輸出結(jié)果:
Line 1 - a is not equal to b Line 2 - a is not equal to b Line 3 - a is not equal to b Line 4 - a is not less than b Line 5 - a is greater than b Line 6 - a is either less than or equal to b Line 7 - b is either greater than or equal to b
相關(guān)文章
Python解決MySQL數(shù)據(jù)處理從SQL批量刪除報錯
這篇文章主要為大家介紹了Python解決MySQL數(shù)據(jù)處理從SQL批量刪除報錯,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12Python利用正則表達式實現(xiàn)計算器算法思路解析
這篇文章主要介紹了Python利用正則表達式實現(xiàn)計算器算法思路解析,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2018-04-04Python?torch.onnx.export用法詳細介紹
這篇文章主要給大家介紹了關(guān)于Python?torch.onnx.export用法詳細介紹的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-07-07Python使用selenium + headless chrome獲取網(wǎng)頁內(nèi)容的方法示例
這篇文章主要介紹了Python使用selenium + headless chrome獲取網(wǎng)頁內(nèi)容的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10使用Pytorch構(gòu)建第一個神經(jīng)網(wǎng)絡(luò)模型?附案例實戰(zhàn)
這篇文章主要介紹了用Pytorch構(gòu)建第一個神經(jīng)網(wǎng)絡(luò)模型(附案例實戰(zhàn)),本文通過實例代碼給大家講解的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03