python string_2 內建函數詳解,string_2函數詳解

來源:互聯網
上載者:User

python string_2 內建函數詳解,string_2函數詳解

先定義2個字串變數

1 #coding:utf-82 3 s1="http"4 s2="http://www.cnblogs.com/sub2020/p/7988111.html"

取得字串長度,備用

print "len(s1):%d , len(s2):%d" %(len(s1),len(s2))

輸出

len(s1):4 , len(s2):45

 

# string.split(str="", num=string.count(str))

#以 str 為分隔字元切片 string,如果 num有指定值,則僅分隔 num 個子字串

list1 = s2.split("/")  #使用 '/'為分隔字元print list1for x,y in enumerate(list1):  #輸出帶索引的list切片    print "list[%d]:%s" %(x,y)

output

list[0]:http:list[1]:list[2]:www.cnblogs.comlist[3]:sub2020list[4]:plist[5]:7988111.html

 

string.capitalize() 把字串的第一個字元大寫

print "s1.capitalize() :",s1.capitalize()

output 第一個字元變為大寫了

s1.capitalize() : Http

string.center(width) 返回一個原字串置中,並使用空格填充至長度 width 的新字串

print "s1.center(10,'*') :", s1.center(10,"*")#當width<len時,原樣返回strprint "s1.center(2)     :", s1.center(2)print "s1.center(5)     :", s1.center(5)

output 當長度小於字串長度時,無變化

s1.center(10,'*') : ***http***s1.center(2)     : https1.center(5)     :  http

# string.count(str, beg=0, end=len(string)) 返回 str 在 string 裡面出現的次數,如果 beg 或者 end 指定則返回指定範圍內 str 出現的次數

01.計算'c'在s2中出現的次數,後兩個參數beg=起始計算位置,預設為[0],end=終止計算位置,預設為字串長度[len(string)],以s2為例即[44](45-1)

print "s2.count('c') :%d" %s2.count('c')

output 全字串檢索'c'

s2.count('c') :2

02.計算'c'在s2中出現的次數,只設定一個參數,預設為beg參數,end參數為預設值

print "s2.count('c',15) :%d" %s2.count('c',15)

output 從第[15]位檢索'c'的出現次數:1次,過濾掉了[15]位之前的一次

s2.count('c',15) :1

03.檢索'p'在[10]-[30]間出現的次數

print "s2.count('p',10,30) :%d" %s2.count('p',10,30)

output 

s2.count('p',10,30) :0

 

# string.find(str, beg=0, end=len(string))
#檢測 str 是否包含在 string 中,如果 beg 和 end 指定範圍,則檢查是否包含在指定範圍內,如果是返回開始的索引值,否則返回-1

01.在s2中全文尋找'c'

print "s2.find('c') :%d" %s2.find('c')

輸出 'c'的索引,找到一個就停止

s2.find('c') :11

02.從索引[15]向後尋找'c'

print "s2.find('c',15) :%d" %s2.find('c',15)

output 找到了第二個'c'

s2.find('c',15) :19

03.在[15]-[30]之間尋找'c'

print "s2.find('p',10,30) :%d" %s2.find('p',10,30)

output

s2.find('p',10,30) :-1

發布至首頁候選區需要字數,哎,我就是想試試,同時也是自學的一部分

讓大家見笑了,如果有錯誤,請指正,新手,有可能某些地方理解錯誤

如果您感覺對您有協助,需要後續,請留言,因為我這麼寫是把代碼拆開詳細解釋了,原始碼都在一起的,以後會整體發布

謝謝捧場!

 

quote:http://www.runoob.com/python/python-strings.html

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.