Python 字符串方法总结
1. str.lower() 将所有字母转换成小写:
>>> "HelLo WoRld!@#".lower() 'hello world!@#'
2. str.upper() 将所有字母转换成大写:
>>> "dd*&..87KDJIkjd".upper() 'DD*&..87KDJIKJD'
3. str.islower() 判断字母是否全部小写:
>>> "ddksdkknb**.234".islower() True >>> "kdjwllL".islower() False
4. str.isupper() 判断字母是否全部大写:
>>> "KDJII**76".isupper() True >>> "ddID!!".isupper() False
5. str.capitalize() 将字符串的第一个字母变成大写,其他字母变小写:
>>> "dSekjg skDDg Wekj".capitalize() 'Dsekjg skddg wekj'
6. str.center(width, fillchar=" ") 方法返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格:
>>> "dkjwi".center(20) ' dkjwi ' >>> "dkjwi".center(50) ' dkjwi ' >>> "dkjwi".center(50, "1") '1111111111111111111111dkjwi11111111111111111111111'
7. str.encode(encoding='UTF-8',errors='strict') 方法将字符串编码成指定格式。errors 参数可以指定不同的错误处理方案:
>>> "test".encode("utf-8") b'test'
8. str.casefold() 将大写转换为小写,不完全和 str.lower() 相同:
>>> "DkwjKJeED".casefold() 'dkwjkjeed' >>> "Groß - α".casefold() # 德语大写 a 'gross - α' >>> "Groß - α".lower() 'groß - α'
9. str.count(sub[, start[, end]]) 用于统计字符串里某个字符出现的次数。sub 是要搜索的字符串,start 是开始搜索位置,end 是搜索结束位置(不搜过 end):
>>> "3kjdij2kj3233dkjY%".count("3") 4 >>> "3kjdij2kj3233dkjY%".count("3", 3) 3 >>> "3kjdij2kj3233dkjY%".count("3", 8, 9) 0 >>> "3kjdij2kj3233dkjY%".count("3", 8, 10) 1
10. str.find(sub[, start[, end]])) 用于检测字符串中是否包含子字符串 str ,如果指定 start 和 end 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回 -1:
>>> "kejlgiw2k24jll".find("l") 3 >>> "kejlgiw2k24jll".find("l", 3) 3 >>> "kejlgiw2k24jll".find("l", 4) 12 >>> "kejlgiw2k24jll".find("l", 4, 10) -1
11. str.expandtabs(tabsize=8) 用于把字符串中的 tab 符号(' ')转为空格,tab 符号(' ')默认的空格数是 8:
>>> " abc".expandtabs() ' abc' >>> " abc".expandtabs(2) ' abc'
12. str.endswith(suffix[, start[, end]]) 用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 "start" 与 "end" 为检索字符串的开始与结束位置(不包括结束位置):
>>> "c:/test/abc.txt".endswith(".txt") True >>> "c:/test/abc.txt".endswith("test", 0, 6) False >>> "c:/test/abc.txt".endswith("test", 0, 7) True
13. format_map(mapping) 类似 str.format(*args, **kwargs) ,不同的是 mapping 是一个字典对象:
>>> dict1 = {"name" : "鱼C论坛", "boss" : "小甲鱼"}
>>> "{name}由{boss}创建".format_map(dict1)
'鱼C论坛由小甲鱼创建'
14. isdigit()、isdecimal() 和 isnumeric() 都是用于判断一个字符串是否全部为数字。
15. str.index(sub[, start[, end]]) 该方法与 str.find() 方法类似,只不过如果str不在 string 中会抛出异常。
16. str.isalpha() 如果字符串全部都是字母(包括汉字),返回 True,否则返回 False:
>>> "测试abc".isalpha() True >>> "space ".isalpha() # 有空格 False >>> "abc123".isalpha() False >>> "abc!".isalpha() False
17. str.isalnum() 如果字符串全部都是字母或者数字(包括汉字),返回 True,否则返回 False:
>>> "你好 hello".isalnum() # 有空格 False >>> "测试".isalnum() True >>> "hello".isalnum() True >>> "hello123".isalnum() True >>> "hello123!".isalnum() False
18. str.isidentifier() 如果字符串是有效标识符,则 isidentifier() 方法返回 True,否则返回 False:
>>> "A1".isidentifier() True >>> "0a".isidentifier() False >>> "_d".isidentifier() True >>> "a-".isidentifier() False >>> "a a".isidentifier() False
19. str.isascii() 如果字符串为空或字符串中的所有字符都是 ASCII,返回 True,否则返回 False:
>>> "测试".isascii() False >>> " ".isascii() True >>> " dd".isascii() True >>> "ab".isascii() # 全角字符 False
20. str.isspace() 如果字符串仅为空格组成,返回 True,否则返回 False:
>>> "".isspace() False >>> " ".isspace() True >>> " 1".isspace() False
21. str.istitle() 方法用于检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写:
>>> "Hello World".istitle() True >>> "Hello world".istitle() False >>> "".istitle() False >>> "123".istitle() False >>> "123a".istitle() False >>> "123A".istitle() True
22. str.rfind(sub[, start[, end]]) 与 str.find() 类似,不同的是该方法是从右到左查找:
>>> "abcdelkjdllsj".rfind("l") 10 >>> "abcdelkjdllsj".rfind("l", 0, 3) -1 >>> "abcdelkjdllsj".rfind("l", 0, 6) 5
23. str.rindex(sub[, start[, end]]) 与 str.index() 类似,不同的是是从右到左查找。
24. str.strip(chars=None) 方法用于移除字符串头尾指定的字符(默认为空格或换行符,该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。):
>>> " ab ck ".strip() 'ab ck' >>> "da dd s ".strip("d") 'a dd s '
25. str.rstrip(chars=None) 与 str.strip() 类似,不同的是该方法是去掉字符串末尾的指定字符(默认为空格或换行符)。
26. str.lstrip(chars=None) 与 str.strip() 类似,不同的是该方法是去掉字符串开头的指定字符(默认为空格或换行符)。
27. str.isprintable() 用于判断字符串中的所有字符都是可打印的,如果是,返回 True,否则返回 False:
>>> "".isprintable() True >>> "abc123 d ".isprintable() True >>> " a".isprintable() False
28. str.join(iterable) 方法用于将序列中的元素以指定的字符连接生成一个新的字符串:
>>> "".join([str(i) for i in range(10)]) '0123456789' >>> "-".join([i for i in "Hello World!"]) 'H-e-l-l-o- -W-o-r-l-d-!' >>> "".join([1, 2, 3]) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> "".join([1, 2, 3]) TypeError: sequence item 0: expected str instance, int found
29. str.ljust(width, fillchar=" ") 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。
如果指定的长度小于原字符串的长度则返回原字符串:
>>> " test".ljust(20) ' test ' >>> " test123 ".ljust(2) ' test123 ' >>> " test123 ".ljust(30, "#") ' test123 #####################'
30. str.rjust(width, fillchar=" ") 方法与 str.ljust() 方法类似,不同的是该方法是右对齐,向左边填充。
31. str.replace(old, new, count=-1) 方法用于将 old 替换为 new,替换 count 次:
>>> "dd2 dkj2 d ".replace("d", "#") '##2 #kj2 # ' >>> "dd2 dkj2 d ".replace("d", "#", 1) '#d2 dkj2 d '
32. str.partition(sep) 方法用于对字符串进行分割,返回一个3元的元组,
第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串:
>>> "abc".partition("|") ('abc', '', '') >>> "fishc.com.cn".partition(".") ('fishc', '.', 'com.cn') >>> "a.b.c.d.e.f".partition(".") ('a', '.', 'b.c.d.e.f')
33. str.rpartition(sep) 方法与 str.partition() 类似,不同的是该方法是从右边开始分隔:
>>> "a.b.c.d.e.f".rpartition(".") ('a.b.c.d.e', '.', 'f') >>> "a.b.c.d.e.f".partition(".") ('a', '.', 'b.c.d.e.f')
34. str.zfill(width) 方法返回指定长度的字符串,原字符串右对齐,前面填充 width 个 0:
>>> "I love FishC.com!".zfill(20) '000I love FishC.com!' >>> "I love FishC.com!".zfill(1) 'I love FishC.com!'
35. str.translate(table) 方法根据 str.maketrans() 方法给出的字符映射转换表转换字符串中的字符。
36. str.maketrans(intab,outtab[,delchars]) 方方法用于给 translate() 方法创建字符映射转换表。
可以只接受一个参数,此时这个参数是个字典类型。对于接受两个参数的最简单的调用方式,
第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串,表示转换的目标。
两个字符串的长度必须相同,为一一对应的关系。在Python3中可以有第三个参数,
表示要删除的字符,也是字符串。一般 maketrans() 方法需要配合 translate() 方法一起使用:
>>> intab = "aeiou" >>> outtab = "12345" >>> deltab = "thw" >>> trantab1 = str.maketrans(intab, outtab) >>> trantab2 = str.maketrans(intab, outtab, deltab) >>> test = "this is string example." >>> print(test.translate(trantab1)) th3s 3s str3ng 2x1mpl2. >>> print(test.translate(trantab2)) 3s 3s sr3ng 2x1mpl2.
37. str.swapcase() 方法用于对字符串的大小写字母进行转换:
>>> "dWdjskjJKsle&&32q**d@Q".swapcase() 'DwDJSKJjkSLE&&32Q**D@q'
38. str.split(sep=None, maxsplit=-1) 通过指定分隔符 sep 对字符串进行切片,如果参数 maxsplit有指定值,则分隔 maxsplit+1 个子字符串:
>>> "hello world".split() ['hello', 'world'] >>> "hello world".split(" ") ['hello', 'world'] >>> "hello world".split() ['hello', 'world'] >>> "hello world".split(" ") ['hello', '', '', '', '', '', '', '', '', 'world'] >>> "hello world".split("o") ['hell', ' w', 'rld'] >>> "hello world".split("o", 1) ['hell', ' world'] >>> "hello world".split("o", 0) ['hello world']
39. str.splitlines(keepends=False) 按照行分隔,返回一个包含各行元素的列表。如果参数 keepends 为 True,保留换行符:
>>> "hello\nworld".splitlines() ['hello', 'world'] >>> "hello\nworld".splitlines(1) ['hello\n', 'world'] >>> "hello\nwor\rld".splitlines(1) # /r 也算 ['hello\n', 'wor\r', 'ld'] >>> "hello\nwor\rld".splitlines() ['hello', 'wor', 'ld']
40. str.format(*args, **kwargs) -> str 用于格式化字符串
41. str.rsplit(sep=None, maxsplit=-1) 与 str.split() 类似,不同的是该方法是从字符串最后面开始分割。
42. str.title() 将所有单词以大写开头,将其他字母变成小写:
>>> "heLLo wOrLD".title() 'Hello World' >>> "123 hello ##6 WorLd".title() '123 Hello ##6 World'
43. str.startswith(prefix[, start[, end]]) -> bool 与 str.endswith() 类似,不同的是该方法是用于判断字符串是否以指定前缀结尾:
>>> "Hello World!".startswith("Hello") True >>> "Hello World!".startswith("hello") False >>> "Hello World!".startswith("World", 6, 11) True

浙公网安备 33010602011771号