python str类型的所有方法

mac2026-06-16  12

1、__contains__和in功能一样(包含)

例子:

name = str("abdc") result = name._contains_("a") print(result) result = "b" in name print(result)

运行得出:

True True

2、getattribute() 反射时用到 3、capitalize(),前字母变成大写或小写 4、center() , 例子:

name = str("abdc") result = name.center(20,"a") print(result)

5、count()计算出现的字符 例子:

name = str("abdc") result = name.count("a"0,2) print(result)

6、encode()转变编码 7、endswith()判断以什么结尾 例子:

name = str("abdc") result = name.endswith("d",0,3) print(result)

8、expandtabs()检测存在"\t"即空格键,可控制生成 例子:

name = str("ab\tdc") result = name.expandtabs(3) print(result)

9、find() 查找字符是否存在,不能用于列表list

例子:

name = str("abdc") result = name.find(a) print(result)

如果包含子字符串返回开始的索引值,否则返回-1。不影响后面程序执行 10、format()字符串拼接 例子:

name = str("ab {0} as {1} dc") result = name.find("dd","ff") print(result)

10、index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。影响后面程序执行 例子:

name = str("abdc") result = name.find(a) print(result)

11、join() 字符串拼接 例子:

name = ["1',"d","c"] result = "".join(name) print(result)

12、l_just()放在左边 13、r_just放在右边 14、lower()变成小写 15、lstrip()只去掉左边空格 16、rstrip()只去掉右边空格 17、partition(),以什么分割,会产生至少3个字符串 例子:

name = "aeiou" result =name.partition("i") print (result);

18、split() 和splitlines() 用换行符分割成列表

name = """s l a s d""" #result = name.split("\n") #result = name.splitlines() print (result);
最新回复(0)