码迷,mamicode.com
首页 > 编程语言 > 详细

python字符串函数

时间:2018-03-20 22:08:07      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:==   argument   序列   imp   ...   only   大写   字符   split   

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 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 >>> 

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 >>> 

 

python字符串函数

标签:==   argument   序列   imp   ...   only   大写   字符   split   

原文地址:https://www.cnblogs.com/ghostwu/p/8613019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!