您的位置:首页 > 编程语言 > Python开发

python中的字符串处理

2017-07-29 20:31 141 查看
1.字符串转换

s.lower() 转为小写

s.upper() 转为大写

s.swapcase() 大写转为小写,小写转为大写

s.capitalize() 首字母大写

转换为int类型 string.atoi(s) 或者int(s)

转换为float类型 string.atof(s) 或者float(s)

转换为long类型 string.atol(s) 或者long(s)

2.查找等操作

s.find(sub,[,start[,end]]) 返回首次出现的位置。找不到返回-1

s.rfind(sub,[,start[,end]]) 返回最后一次出现的位置。找不到返回-1

s.index(sub[,start[,end]]) 与find()功能类似。找不到则传出ValueEerror

s.rindex(sub[,start[,end]]) 与rfind()功能类似,找不到则传出ValueError

s.count(sub[,start[,end]]) 返回子串出现的次数

s.replace(old,new[,maxreplace]) 替换字符串,指定maxreplace时。仅仅替换前maxreplace个

s.strip(char) 删除開始和结尾处的char

s.split([,seq[,maxsplit]]) 返回切割字符串的列表

s.join([sep]) 连接字符串

3.位置

s.ljust(width[,fillchar]) 左对齐

s.rjust(width[,fillchar]) 右对齐

s.center(width[,fillchar]) 居中

s.zfill(width) 左边补零直到长度到width

4.格式化输出

format能够改变字符串的输出形式,举例为:

‘{0},{2},{1}’.format(‘a’,’b’,’c’)

这里{0} {1} {2}分别指代’a’ ‘b’ ‘c’

也能够依照名称来写:

‘cordix:{x},{y}’.format(x=’1’,y=’2’)

字符串的左对齐也能够用format

‘{:<10}’.format(“hello”) 左对齐,宽度为10

‘{:>10}’.format(“hello”) 右对齐。宽度为10

‘{:^10}’.format(“hello”) 居中,宽度为10
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: