python常用模块介绍之一:string模块

简介:

       string模块主要用于对字符串进行操作。string里的许多特性都已经移植到str和unicode对象的方法里去了。下面主要讨论下string模块的常用方法。

  • 函数

1.        string.atof(s) 字符串转换成浮点型

string.atof('1.11')

输出结果:1.11

string.atof('1')

输出结果:1.0

 

2.        string.atoi(s[, base]) 字符串转换成整型

string.atoi('11') or string.atoi('11', 10)

输出结果:11

string.atoi('11', 2)

输出结果:3

string.atoi('11', 8)

输出结果:9

string.atoi('11', 16)

输出结果:17

 

3.        string.capitalize(s) 字符串的第一个字符转换成大写

string.capitalize('hello world')

输出结果:Hello world

 

4.        string.capwords(s[, sep]) 字符串以sep为分隔符分割后的每个字段的首位转换为大写

string.capwords('hello world')

输出结果:Hello World

string.capwords('hello world', 'l')

输出结果:HellO worlD

 

5.        string.center(s, len[, fillchar])字符串转换成指定长度,不够的用fillchar补充,且补充的字符在两边

string.center('hello world', 10, '*')

输出结果:hello world

string.center('hello world', 15, '*')

输出结果:**hello world**

 

6.        string.count(s, sub[, start[, end]])查询sub在s中的个数

string.count('hello world', 'l')

输出结果:3

string.count('hello world', 'l', 3)

输出结果:2

string.count('hello world', 'l', 3, 6)

输出结果:1

7.        string.find(s, sub[, start,[end]]) 查询sub在s中的第一个位置

string.find('hello world', 'l')

输出结果:2

string.find('hello world', 'l', 4, 6)

输出结果:-1

 

8.        string.ljust(s, len[, fillchar])字符串左对齐,不够用fillchar补充

string.ljust('hello world', 15)

输出结果:hello world

string.ljust('hello world', 15, '*')

输出结果:hello world****

 

9.        string.lstrip(s[, chars]) 清除左边的空白字符

string.lstrip(' hello world')

输出结果:hello world

string.lstrip('hello world', 'h')

输出结果:ello world

 

10.    string.upper(s) 字符串转换成大写的

string.upper('hello world')

输出结果:HELLO WORLD

 

11.    string.join(list[, sep]) list里的字符串用sep连接起来

string.join(['hello', 'world'])

输出结果:hello world

string.join(['hello', 'world'], '*')

输出结果:hello*world

 

12.    string.replace(s, old, new[,max]) 字符串s里的old替换为new,最多替换为max次

string.replace('hello world', 'l', 'L')

输出结果:heLLo worLd

string.replace('hello world', 'l', 'L', 1)

输出结果:heLlo world

 

13.    string.translate(s, table[,delchar]) 字符串转换为指定的table里的字符,且删除指定的delchar

table = string.maketrans('hello', 'HELLO')

string.translate('hello world', table)

输出结果:HELLO wOrLd

string.translate('hello world', table, 'l')

输出结果:HEO wOrd

 

14.    string.split(s[, sep[,maxsplit]])  字符串以sep作为分隔符,maxsplit作为分隔次数进行分隔

string.split('hello world')

输出结果:['hello', 'world']

string.split('hello world', 'l')

输出结果:['he', '', 'o wor', 'd']

string.split('hello world', 'l', 1)

输出结果:['he', 'lo world']

  • 模板

map = {'var': 'hello world'}

tmp = string.Template('my first output:${var}')

tmp.substitute(map)

输出结果:my first output: hello world

tmp.safe_substitute(map)

输出结果:同上

 

map = {'var': 'hello world'}

tmp = string.Template('my first output:${vars}')

tmp.substitute(map)

输出结果:

tmp.safe_substitute(map)

输出结果:my first output: ${vars}

 

你可能感兴趣的:(python)