Python的字符串

Python有内置的字符串类型, 内置的字符串是序列(Sequence), 是不可变的序列,  因此不可变序列通用的方法对其都适用.html

 

 

对Python2, 内置的字符串类型有strunicodepython

Python2git

'abc' 是str, u'中国123'  是unicode函数

# Python2.7
>>> type('abc')
<type 'str'>
>>> type(u'中国123')
<type 'unicode'>

 

若是咱们使用Python2, 应该都尽可能使用unicode,就算是纯英文的. 编码

 

Python3spa

但在Python3中, 没有预约义unicode类型了,内置字符串就是str, 可是str中的字符都是unicode编码的 code

#Python3.3
>>> type(u'中国')
<class 'str'>
>>> type('abc')
<class 'str'>
>>> type(str)
<class 'type'>
>>> type(unicode)
NameError: name 'unicode' is not defined

 

 

 

 

下面讨论一些Python内置字符串经常使用的方法, Python2中这些方法对str和unicode基本都是同样的, 没有讨论到的去文档查阅就行,基本上须要的功能都有方法实现.htm

 

字符串分隔, split对象

str.split()接受分隔字符串, 返回分隔后的一个listblog

>>> s = 'wangyu@lvye.cn'
>>> s.split('@')
['wangyu', 'lvye.cn']

 

若是同一个分隔符连续多个存在,则在返回结果中会有空字符串

>>> s = 'wangyu@@@@lvye.cn'
>>> s.split('@')
['wangyu', '', '', '', 'lvye.cn']

4个连续的@产生了3个空串

 

当分隔字符串是多字符的,必须是全匹配

>>> s = 'abc<>cba'
>>> s.split('<>')
['abc', 'cba']

 

 一个反面例子

>>> s = 'abc<>cba%$acb'
>>> s.split('<>$')
['abc<>cba%$acb']

 

str.split()也能够不接受参数,这时候是使用空格作分隔,且不产生空串,若是开头和结尾有空格,也会被忽略掉

>>> s = ' we are the   champion'
>>> s.split()
['we', 'are', 'the', 'champion']

 

 

子串替换

  str.replace(old, new [, count])

replace把old替换成new,而且能够指定替换个数, 并且函数返回一个copy,不会影响原来的str对象.

>>> s = 'he is nate, nate is his name'
>>> s.replace('nate', 'sky')
'he is sky, sky is his name'
>>> s
'he is nate, nate is his name'

 

 

 

 

子串查找

字串查找用find()或index(),  其中index()是序列通用的方法

不一样的是若没找到find()返回-1, index()抛出异常ValueError, 找到返回字串索引.

find()和index()的语法相同

 

str.find(substr [, start [, end]])

 

普通使用

>>> s='we are are the champion'
>>> s.find('ar')
3

加上范围

>>> s='we are are the champion'
>>> s.find('ar', 4)
7

 

注意,若是只是想知道一个字符串是否包含一个子串,使用 in 

>>> s = 'we are the champion'
>>> 'are' in s
True

 

 

字符串的strip

一样的strip会copy一份原来的字串进行处理.

不加任何参数,去除左右的空格

>>> s = '    www.lvye.cn  '
>>> s.strip()
'www.lvye.cn'

 

带上参数

>>> s.strip('wcn. ')
'lvye'

注意带上参数时,空格要显示指定.

strip还能够去除两端的换行符

 

 

字符串其它的方法

  •  isalpha()  是否都是字母
  •  isdigit()    是否都是数字
  •  upper()    都转化为大写

 

Python str的方法,Python文档中很全.

------------------------- 

 参考:

http://docs.python.org/3/library/stdtypes.html#str   Python文档

相关文章
相关标签/搜索