python字符串(一)

变量命名规则

在讲解python字符串之前,先穿插一下变量的命名规则:

1、变量名只能包含字母、数字和下划线,不能以数字开头

2、变量名不能包含空格,可以使用下划线分隔其中的单词

3、不要将python关键字和函数名用作变量名

4、变量应该既简单又具有描述性

5、谨慎使用小写字母i和大写字母O,容易看成0和1


字符串

    ——使用单引号'  ' 或 双引号"  " 或三引号"""   """括起来的一串字符

 python字符串有很多方法,大致分为以下几类:

字符串方法:

一、变形     lower  upper  capitalize  title  swapcase  

string.lower()  

  ——将字符串全部变成小写

string.upper()

  ——将字符串全部变成大写

string.capitalize()

  ——将字符串首字母大写

string.title()

  ——将每一个单词的首字母大写,并将单词中非首字母转换成小写

string.swapcase()

  ——将字符串大写字母变为小写字母,小写字母变为大写字母

下面依依举例说明:

>>> str1="hello    world!"
>>> str1.lower()
'hello    world!'
>>> str1.upper()
'HELLO    WORLD!'
>>> str1.capitalize()
'Hello    world!'
>>> str1.title()
'Hello    World!'
>>> str1.swapcase()
'HELLO    WORLD!'

二、删减   strip  lstrip   rstrip 

string.strip([chars])

  ——去除字符串两端的空白符

string.lstrip([chars])

  ——去除字符串左边的空白符

string.rstrip([chars])

  ——去除字符串右边的空白符

下面依依列举说明:

>>> str2="   hello   world!   "
>>> print(str2)
   hello   world!
>>> str2.strip()
'hello   world!'
>>> str2.lstrip()
'hello   world!   '
>>> str2.rstrip()
'   hello   world!'

三、分切   partition   rpartition   splitlines   split   rsplit 

string.partition(sep)

  ——此方法返回一个三元的tuple,分别是 sep左边的字符串,分隔符sep本身和分隔符sep右边的字符串

>>> str1="http://www.cnblogs.com/kudangren/"
>>> str1.partition("://")
('http', '://', 'www.cnblogs.com/kudangren/')

string.rpartition(sep)

  ——与partition一样,不同的是从右到左开始匹配

string.splitlines(keepends)

  ——Python splitlines() 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

  keepends -- 在输出结果里是否去掉换行符('\r', '\r\n', \n'),默认为 False,不包含换行符,如果为 True,则保留换行符。

>>> str1 = 'ab c\n\nde fg\rkl\r\n'
>>> str1.splitlines()
['ab c', '', 'de fg', 'kl']

>>> str2 = 'ab c\n\nde fg\rkl\r\n'
>>> str2.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

 

string.split([sep[,maxsplit]])

  ——通过指定分隔符对字符串进行切片,返回分割后的字符串列表。如果参数maxsplit有指定值,则仅分隔 maxsplit 个子字符串

>>>a="alvy.test.txt"
>>>a.split('.')
['yl','text','txt']

>>>a.split('.',1)
['alvy','test.txt']

 

string.rsplit([sep[,maxsplit]])

  ——同split,不同的是从右开始分割,还以字符串a举例,应用此方法我们可以判定文件类型

>>>a.rsplit('.',1)
['alvy.test','txt']

 

四、连接      join 

string.join(seq)

  ——join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

  seq:要连接的元素序列

例1

>>> str1="-"
>>> seq=["2017","12","11"]
>>> str1.join(seq)
'2017-12-11

例2

conf = {'host':'127.0.0.1',
...     'db':'spam',
...     'user':'sa',
...     'passwd':'eggs'}

>>> ';'.join("%s=%s"%(k, v) for k, v in conf.iteritems())
'passswd=eggs;db=spam;user=sa;host=127.0.0.1'

 

五、判定      isalnum  isalpha  isdigit  islower  isupper  isspace  istitle  startswith  endswith   

string.isalnum()

  -检测字符串是否由字母和数字组成,如果string至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False。

 

>>> str = "this2009"  # 字符中没有空格
>>> str.isalnum()
True

>>> str = "this is string example....wow!!!">>> str.isalnum()
False

 

string.isalpha()

  -检测字符串是否只由字母组成,如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False。

 

>>> str = "this"   # No space & digit in this string
>>> str.isalpha()
True

>>> str = "this is string example....wow!!!"
>>> str.isalpha()
False

 

string.isdigit()

  -检测字符串是否只由数字组成,如果字符串只包含数字则返回 True 否则返回 False。

 

>>> str = "19920323"   # No space & digit in this integer
>>> str.isalpha()
True

>>> str = "this is string example....wow!!!"
>>> str.isalpha()
False

 

string.islower()

  -检测字符串是否由小写字母组成,如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False。

 

>>> str = "bu dao weng xiansheng"
>>> str.isalpha()
True

>>> str = "This is string example....wow!!!"
>>> str.isalpha()
False

 

string.isupper()

  -与islower相反,可以islower做为参照。

 

string.isnumeric()

  -检测字符串是否只由数字组成。这种方法是只针对unicode对象。

  注:定义一个字符串为Unicode,只需要在字符串前添加 'u' 前缀即可,具体可以查看本章节例子。

 

>>> str = u"this2009"
>>> str.isnumeric()
False

>>> str = u"23443434"
>>> str.isnumeric()
True

 

string.isspace()

  -检测字符串是否只由空格组成,如果字符串中只包含空格,则返回 True,否则返回 False。

 

>>> str="    "
>>> str.isspace()
True

>>> str="hellow   world!"
>>> str.isspace()
False

 

string.istitle()

  -检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写,如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False

 

>>> str = "This Is String Example...Wow!!!"
>>> print str.istitle()
True

>>>str = "This is string example....wow!!!"
>>> print str.istitle()
False

 

string.startswith(prefix[,start[,end]])

  -用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 start 和 end 指定值,则在指定范围内检查。

  1. prefix--检测的字符串
  2. start--可选参数用于设置字符串检测的起始位置
  3. end--可选参数用于设置字符串检测的结束位置。

 

>>> str = "this is string example....wow!!!";
>>> str.startswith( 'this' )
True

>>> str.startswith( 'is', 2, 4 )
True

>>> str.startswith( 'this', 2, 4 )
False

 

string.endswith(suffix[,start[,end]])

  -用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

  1. suffix--该参数可以是一个字符串或者是一个元素
  2. start--字符串中的开始位置
  3. end--字符中结束位置
>>> str = "this is string example....wow!!!"
>>> suffix = "wow!!!"

>>> str.endswith(suffix)
True

>>> str.endswith(suffix,20)
True

>>> suffix = "is"
>>> str.endswith(suffix, 2, 4)
True

>>> str.endswith(suffix, 2, 6)
False

 

六、查找      count  find  index  rfind  rindex 

string.count(sub[,start[,end]])

  -用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

  1. sub--搜索的子字符串
  2. start--字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0
  3. end--字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置
>>> str = "this is string example....wow!!!"
>>> sub="i"
>>> str.count(sub,4,40)
2

>>> sub="wow"
>>>str.count(sub)
1

string.find(sub[,start[,end]])

  -检测字符串中是否包含子字符串 sub,如果指定 start(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

  1. sub--指定检索的字符串
  2. start--开始索引,默认为0
  3. end--结束索引,默认为字符串的长度
>>> str1 = "this is string example....wow!!!"
>>> str2="exam"

>>> str1.find(str2)
15
>>> str1.find(str2, 10)
15
>>> str1.find(str2, 40)
-1

string.index(sub[,start[,end]])

  -检测字符串中是否包含子字符串 sub ,如果指定 start(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果sub不在 string中会报一个异常。返回索引值或抛出异常

Traceback (most recent call last):
  File "test.py", line 8, in 
  print str1.index(str2, 40);
ValueError: substring not found

 

string.rfind(sub[,start[,end]])

  - 返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。

string.rindex(sub[,start[,end]])

  -返回子字符串 sub 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[start:end]设置查找的区间。

七、替换      replace  translate  

string.replace(old,new[,max])

  -把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次

string.translate(table[,deletechars])

  -根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中

  1. table -- 翻译表,翻译表是通过maketrans方法转换而来
  2. deletechars -- 字符串中要过滤的字符列表。
 1 #!/usr/bin/python
 2 
 3 from string import maketrans   # 引用 maketrans 函数。
 4 
 5 intab = "aeiou"
 6 outtab = "12345"
 7 trantab = maketrans(intab, outtab)
 8 
 9 str = "this is string example....wow!!!"
10 print str.translate(trantab)

以上实力输出结果如下:

th3s 3s str3ng 2x1mpl2....w4w!!!

以上实例去除字符串中的 'x' 和 'm' 字符:

1 from string import maketrans   # Required to call maketrans function.
2 
3 intab = "aeiou"
4 outtab = "12345"
5 trantab = maketrans(intab, outtab)
6 
7 str = "this is string example....wow!!!"
8 print str.translate(trantab, 'xm')

以上实力输出结果如下:

th3s 3s str3ng 21pl2....w4w!!!

八、编码      encode  decode 

string.encode([encoding[,errors]])

  -以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

  1. encoding--要使用的字符串编码,如“UTF-8”
  2. errors--设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
>>> str = "this is string example....wow!!!"
print "Encoded String: " + str.encode('base64','strict')

Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=

string.decode([encoding[,errors]])

  -以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。

  1. encoding--要使用的编码,如"UTF-8"。
  2. errors--设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
1 str = "this is string example....wow!!!"
2 str = str.encode('base64','strict')
3 
4 print "Encoded String: " + str
5 print "Decoded String: " + str.decode('base64','strict')

以上实力输出结果如下:

Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=

Decoded String: this is string example....wow!!!

九、填充      center  ljust  rjust  zfill  expandtabs 

string.center(width[,fillchar])

  -返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。

>>> str1="lei"
>>> str1.center(10,'&')
'&&&lei&&&

string.ljust(width[,fillchar])

  -返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

>>> str1="jiaxiaolei"
>>> str1.rjust(20,"@")
'@@@@@@@@@@jiaxiaolei'

string.rjust(width[,fillchar])

  -返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。

string.zfill(width)

  -返回指定长度的字符串,原字符串右对齐,前面填充0

string.expandtabs([tabsize])

  -把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。

posted @ 2017-12-12 13:16  kudangren  阅读(454)  评论(0编辑  收藏  举报