Python开发笔记之-字符串函数

        1.首字母大写

>>> s = 'yuanzhumuban'
>>> s.capitalize()
'yuanzhumuban'

    2.replace,替换  

>>> s = 'my name is yuanzhumuban, age is 20'
>>> s
'my name is yuanzhumuban, age is 20'
>>> s.replace( '20', '30' )
'my name is yuanzhumuban, age is 30'
>>> s
'my name is yuanzhumuban, 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个参数,第一个需要替换的字符,第二个用什么字符去替换,第三个替换的次数,如果不传,默认全部替换

 str = '121212'
str.replace( '1', 'g' )
 'g2g2g2'
 str.replace( '1', 'g', 1 )
 'g21212'
str.replace( '1', 'g', 2 )
 'g2g212'
str.replace( '1', 'g', 3 )
 '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 string
2 >>> 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 >>> 

  

    

  

转载于:https://www.cnblogs.com/68xi/p/8616448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值