《Python for Data Analysis》
Python 字符串对象方法
方法 | 说明 |
---|---|
count | 返回子串在字符串中出现次数 |
endswith 、startwith | 如果字符串以某个后缀结尾或前缀开头,返回True |
join | 连接其他字符串序列的分隔符 |
index | 返回子串第一个字符所在位置,如果没有,ValueError |
find | 返回子串第一次发现的第一个字符所在的位置,如果没有,返回-1 |
rfind | 返回子串最后一个发现的子串的第一个字符的位置,如果没有,返回-1 |
replace | 用另一个字符串替换指定子串 |
strip 、rstrip、lstrip | 去除空白符 |
split | 通过指定的分隔符将字符串拆分为一组子串 |
lower、upper | 将字母字符转换为小写或大写 |
ljust、rjust | 用空格填充字符串的空白侧以返回符合最低宽度的字符串 |
In [32]: val = 'a,b, guido'
In [33]: val.split(',')
Out[33]: ['a', 'b', ' guido']
In [34]: pieces = [x.strip() for x in val.split(',')]
In [35]: pieces
Out[35]: ['a', 'b', 'guido']
In [36]: first, second, third = pieces
In [37]: first + '::' + second + '::' + third
Out[37]: 'a::b::guido'
In [38]: '::'.join(pieces)
Out[38]: 'a::b::guido'
In [39]: 'guido' in val
Out[39]: True
In [40]: val.index(',')
Out[40]: 1
In [41]: val.find(':')
Out[41]: -1
In [42]: val.count(',')
Out[42]: 2
In [43]: val.replace(',', '::')
Out[43]: 'a::b:: guido'
正则表达式
方法 | 说明 |
---|---|
findall、finditer | 返回字符串中所有非重叠匹配模式。findall返回的是由所有模式组成的列表,而finditer返回一个迭代器 |
match | 从字符串起始位置匹配模式,还可以对模式各个部分进行分组。如果匹配到模式,返回一个匹配项对象,否则返回None |
search | 扫描整个字符串以匹配模式。 |
split | 根据找到的模式将字符串拆分为数段 |
sub、subn | 将字符串中所有的sub和前n个subn模式替换为指定表达式。在替换字符串中可以通过\1、\2等符号表示各分组项。 |
In [44]: import re
In [45]: text = "foo bar \t baz \tqux"
In [46]: text
Out[46]: 'foo bar \t baz \tqux'
In [47]: re.split('\s+', text)
Out[47]: ['foo', 'bar', 'baz', 'qux']
In [48]: regex = re.compile('\s+')
In [49]: regex.split(text)
Out[49]: ['foo', 'bar', 'baz', 'qux']
In [50]: regex.findall(text)
Out[50]: [' ', ' \t ', ' \t']
注: 如果打算对许多字符串应用同一条正则表达式,强烈建议通过re.compile
创建regex对象。这样可以节省大量的CPU时间。