python字串函數,python字串

來源:互聯網
上載者:User

python字串函數,python字串

1,首字母大寫

>>> s = 'ghostwu'>>> s.capitalize()'Ghostwu'

2,replace,替換

>>> s = 'my name is ghostwu, age is 20'>>> s'my name is ghostwu, age is 20'>>> s.replace( '20', '30' )'my name is ghostwu, age is 30'>>> s'my name is ghostwu, age is 20'>>> 

查協助

>>> help( str.replace )

如果是面向過程的函數用法,直接help( 函數名 ),如help( abs )

用法說明:

replace(...)
S.replace(old, new[, count]) -> string

Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.

接受3個參數,第一個需要替換的字元,第二個用什麼字元去替換,第三個替換的次數,如果不傳,預設全部替換

1 >>> str = '121212'2 >>> str.replace( '1', 'g' )3 'g2g2g2'4 >>> str.replace( '1', 'g', 1 )5 'g21212'6 >>> str.replace( '1', 'g', 2 )7 'g2g212'8 >>> str.replace( '1', 'g', 3 )9 'g2g2g2'

3,split:切割

 1 >>> ip='127.0.0.1' 2 >>> ip 3 '127.0.0.1' 4 >>> ip.split( '.' ) 5 ['127', '0', '0', '1'] 6 >>> ip.split( '.', 1 ) 7 ['127', '0.0.1'] 8 >>> ip.split( '.', 2 ) 9 ['127', '0', '0.1']10 >>> ip.split( '.', 3 )11 ['127', '0', '0', '1']12 >>> 

4,用string模組,用法如下:

1 >>> import string2 >>> help( string.capitalize )3 4 >>> s = 'ghostwu'5 >>> string.capitalize( s )6 'Ghostwu'
 1 >>> import string 2 >>> s = 'my name is ghostwu, age is 20' 3 >>> string.replace( s, '20', '30' ) 4 'my name is ghostwu, age is 30' 5 >>> ip 6 '127.0.0.1' 7 >>> string.split( ip, '.' ) 8 ['127', '0', '0', '1'] 9 >>> string.split( ip, '.', 1 )10 ['127', '0.0.1']11 >>> 

5,filter:過濾, 利用這個函數,篩選出一個序列的偶數

 1 >>> def isEven( n ): 2 ...     if n % 2 == 0: 3 ...             return True 4 ...  5 >>> isEven( 10 ) 6 True 7 >>> isEven( 3 ) 8 >>> range( 10 ) 9 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]10 >>> l = range( 10 )11 >>> filter( isEven, l )12 [0, 2, 4, 6, 8]13 >>> 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.