首页 > 技术文章 > python 字符串方法

jingxindeyi 2020-08-07 00:39 原文

字符串方法

1、大小写转换

方法 描述
s.capitalze() 首字母大写
s.title() 标题格式(单词首字母大写)
s.upper() 转换为大写
s.lower() 转换为小写
s.swapcase() 大小写互换

2、类型检查(数字,字母)

方法 描述
s.isalnum() 检查所有字符串是否只有数字和字母,返回结果为True或False
s.isalpha() 检查字符串中是否只有字母
s.isdigit() 检查字符串字符是否全为数字
s.islower() 检查字符串字符是否全为小写
s.isupper() 检查字符串字符是否全为大写
s.istitl() 检查字符串字符是否为标题式样
s.startswith() 检查字符串字符是否以特定字符开头
s.endswith() 检查字符串字符是否以特定字符结尾
s.isspace() 检查字符串字符是否全是空白

3、分割、去除(首尾)、连接、对齐

方法 描述
s.split([sep[,maxsplit]]) 以sep(默认空白字符)为分隔符截取字符串,maxsplit为截取次数
s.rsplit([sep[,maxsplit]]) 从右开始,以 sep 为分隔符截取字符串,maxsplit为截取次数(若不指定,同split())
s.spartition(sep) 用sep分割s,返回元祖(head,sep,tail),为找到sep返回(s,"","")
s.strip([chrs]) 去除字符串两头的chrs(默认为空白)的字符
s.lstrip([chrs]) 去除字符串左端的chrs(默认为空白)的字符
s.rstrip([chrs]) 去除字符串右端的chrs(默认为空白)的字符
s.join(t) 以s作为连接符,连接序列t的元素,得到新的字符串
s1 + s2 连接s1和s2
s.rjust(width [, fill]) 在长度为width的字符串中右对齐s,长度不够用fill补齐
s.ljust(width [, fill]) 在长度为width的字符串中左对齐s,长度不够用fill补齐
s.center(width [, pad])

4、查找,替换

方法 描述
s.count(sub [,start [,end]]) 计算sub在s中出现的次数
s.find(sub [,start [,end]]) 返回sub首次出现的位置,否则返回-1
s.rfind(sub [,start [,end]]) 返回sub最后出现的位置,否则返回-1
s.index(sub [,start [,end]]) 返回sub首次出现的位置,否则报错
s.rindex(sub [,start [,end]]) 返回sub最后出现的位置,否则报错
s.replace(old,new [, maxreplace]) 用new替换old,maxreplace是最大替换次数

5、format格式化字符串

s.format(*aarg, **kargs)
#! /usr/bin/python3
# -*- congfig:utf-8 -*-

def test():
    h = "hello"
    w = "world"
    f1 = "{} {}".format(h,w)
    print(f1)
    f2 = "{1} {0}".format(w,h)
    print(f2)
    f3 = "{h} {w}".format(w=w,h=h)
    print(f3)
    t = {"h":"hello","w":"world"}
    f4 = "{h} {w}".format(**t)
    print(f4)

if __name__ == "__main__":
    test()
hello world
hello world
hello world
hello world

数字格式化

>>> print("{:.2f}".format(3.1415926));
3.14
数字 格式 输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:>10d}                13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d}        13    中间对齐 (宽度为10)
11 '{:b}'.format(11)
'{:d}'.format(11)
'{

推荐阅读