python-str对象及操作

来源:互联网 发布:淘宝发货物流其他 编辑:程序博客网 时间:2024/06/06 02:13
Python中,字符串是 不可变 的序列,支持:重复、连接、索引和切片等操作,例如:
 s * n     # 将 s 重复n次
 s1 + s2   # 将字符串 s1 和 s2 连接
 s[0]      # 索引字符串 s1 中的第一个字符
 s[0:2]    # 返回字符串 s 中的前两个字符

1.首字母大写
    str.capitalize()
    返回s的一份拷贝,并不改变s。如果 s 的首字符是一个字母,则拷贝的首字母将其改成大写,其余所有字母转成小写。


2.对齐方式:
    1)左右对齐:
    str.ljust(width[, fillchar]) /  s.rjust(width[, fillchar])
    返回一个长度为 max(len(s), width) 的字符串,如果 width > len(s),则左/右对齐,并在另一端填充 fillchar
   
    2)居中
    str.center(n, fillchar=' ')
  返回一个新的字符串,新字符串的长度为 max(len(s), n),当 n > len(s)时,使用参数 fillchar (默认为空格)填充新字符串中其余的位置,并将 s 置于新字符串的中部,当左右无法均衡填充时,优先填充左侧。


3.计数
    s.count(sub, start=0, end=sys.maxint)
  统计 s[start:end] 中,子串 sub 出现的次数。


4.定位
    1)定位不到时返回 -1  
    s.find(sub [,start [,end]]) /  s.rfind(sub [,start [,end]])
    返回 int 型结果,表示 sub 在 s[start:end] 中第一次出现的下标。如果在 s[start:end] 中没有找到子串 sub,则返回 -1。
'''
>>> 'testtest'.find('est')
1
>>> 'testtest'.find('tt')
3
>>> 'testtest'.find('tt',3)
3
>>> 'testtest'.find('tt',4)
-1
'''   
    2)定位不到时抛出异常
    s.index(sub [,start [,end]])<br>s.rindex(sub [,start [,end]])
    功能与 find() 类似,但是如果没有找到 sub ,则抛出 ValueError


5.内容形式判断
    isalnum()、isalpha()、isdigit()、isspace()
   
    s.isalnum()
  返回布尔型结果,
  判断 s 是不是非空,且全部由 字母 和 数字 组成。
 
    s.isalpha()
  返回布尔型结果,
  判断 s 是不是非空,且全部由 字母 组成。
 
    s.isdigit()
  返回布尔型结果,
  判断 s 是不是非空,且全部由 数字 字符组成。
  
    s.isspace()
  如果 len(s) > 0,且其中的所有字符都是空格,则返回True;
  如果 s 为空,或s中存在至少一个非空格的字符,则返回False。


6.连接
    s.join(iterable)
  以 s 为分隔符连接 iterable 中的字符串
例如:
>>> '$'.join(['hello','this','world'])
>>> 'hello$this$world'


7.拆分
    1)保留分隔符的一次拆分  
    s.partition(sep)<br>s.rpartition(sep)
  以 sep 为分隔符拆分 s ,返回 (head, sep, tail) 形式的三元组。
例如:
>>> 'hello$this$world'.partition('$')
    ('hello', '$', 'this$world')
>>> 'hello$this$world'.rpartition('$')
    ('hello$this', '$', 'world')<br>>>> 'hello this world'.partition('$')<br>('', '', 'hello this world')
  
    2)不保留分隔符的完全拆分  
    split()、rsplit()、splitlines()
    s.split([chars])<br>s.rsplit([sep [,maxsplit]])<br>s.splitlines(keepends=False)
例如:
>>> 'hello$this$world'.split('$')
    ['hello', 'this', 'world']


8.删除部分字符串内容
s.lstrip([chars]) #从开头删除
s.strip([chars]) # 左右两端同时删除
s.rstrip([chars]) # 从结尾删除

9.替换
s.replace(old, new[, count])
原创粉丝点击