python之字符串类详解
在python中,加了引号的字符被认为是字符串。
1、capitalize()
把字符串的第一个字符大写
>>> s = "hello"
>>> s.capitalize()
'Hello'
2、casefold()
转换字符串中所有大写字符为小写,两者的区别是:lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold() 方法。
>>> s = "HELLO"
>>> s.casefold()
'hello'
3、center(width,fillchar='')
center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。下面以填充"*"举例:
>>> s = "hello"
>>> s.center(10,"*")
'**hello***
4、count(str, beg=0, end=len(string))
返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
>>> s="hello"
>>> s.count("l")
2
5、encode(self, /, encoding='utf-8', errors='strict')
以 encoding 指定的编码格式解码 string,如果出错默认报一个 ValueError 的 异 常 , 除非 errors 指 定 的 是 'ignore' 或 者'replace'
>>> s = "你好"
>>> s.encode()
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> s = "hello"
>>> s.encode()
b'hello'
>>>
6、str.endswith(obj, beg=0, end=len(string))
检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.
如下例判断字符串“hello”是否以字符“o”结束
>>> s="hello"
>>> s.endswith("o")
True
>>> s.endswith("a")
False
7、str.expandtabs(tabsize=8)
把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8。
>>> s=" this is a tap"
>>> s.expandtabs()
' this is a tap'
8、str.find(str, beg=0, end=len(string))
检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
>>> s="hello"
>>> s.find("el")
1
>>> s.find("a")
-1
>>> s.find("h")
0
9、str.format(*args, **kwargs)
格式化字符串
{}个数等于参数
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
>>> print("my name is {},i am {} years old".format("kevin",10))
my name is kevin,i am 10 years old
{}个数大于参数
>>> print("my name is {},i am {} years old".format("kevin",10,"hello"))
my name is kevin,i am 10 years old
{}个数小于参数
>>> print("my name is {},i am {} years old".format("kevin"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
10、str.format_map(mapping)
类似 str.format(*args, **kwargs) ,不同的是 mapping 是一个字典对象。
>>> People = {"name": "john", "age": 33}
>>> print("My name is {name},iam {age} old".format_map(People))
My name is john,iam 33 old
11、str.index(str, beg=0, end=len(string))
跟find()方法一样,只不过如果str不在 string中会报一个异常.
>>> s="hello"
>>> s.index("2")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.index("e")
1
12、str.isalnum()
如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
>>> s = "hello"
>>> s.isalnum()
True
>>> s="!@#$"
>>> s.isalnum()
False
13、str.isalpha()
如果 string 至少有一个字符并且所有字符都是字母则返回 True,
否则返回 False
>>> s="123456"
>>> s.isalpha()
False
>>> s="hello"
>>> s.isalpha()
True
14、str.isascii()
如果字符串为空或字符串中的所有字符都是 ASCII,则返回 True,否则返回 False。
>>> s="hello"
>>> s.isascii()
True
>>> s="中国"
>>> s.isascii()
False
15、str.isdecimal()
如果 string 只包含十进制数字则返回 True 否则返回 False.
>>> s="1234"
>>> s.isdecimal()
True
>>> s="123hello"
>>> s.isdecimal()
False
16、str.isdigit()
如果 string 只包含数字则返回 True 否则返回 False.
>>> s="12345"
>>> s.isdigit()
True
>>> s="123aed"
>>> s.isdigit()
False
17、str.isidentifier()
用于判断字符串是否是有效的 Python 标识符,可用来判断变量名是否合法。如果字符串是有效的 Python 标识符返回 True,否则返回 False。
>>> s="hello"
>>> s.isidentifier()
True
>>> s="123"
>>> s.isidentifier()
False
18、str.islower()
如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
>>> s="hello"
>>> s.islower()
True
>>> s="Hello"
>>> s.islower()
False
19、str.isnumeric()
如果 string 中只包含数字字符,则返回 True,否则返回 False
>>> s="123456"
>>> s.isnumeric()
True
>>> s="123hello"
>>> s.isnumeric()
False
20、str.isprintable()
如果字符串中的所有字符都可打印或字符串为空,则返回 True,否则返回 False。
非打印字符是指在 Unicode 字符数据库中定义为“其他”或“分隔符”的字符,但 ASCII 空格(0x20)除外,它被认为是可打印的。(请注意,此上下文中的可打印字符是在对字符串调用 repr( ) 时不应转义的字符。它与写入的字符串的处理无关系统标准输出或者系统标准。)
>>> s="hello"
>>> s.isprintable()
True
>>> s="\nabc"
>>> s.isprintable()
False
21、str.isspace()
如果 string 中只包含空格,则返回 True,否则返回 False.
>>> s="hello world"
>>> s.isspace()
False
>>> s=" "
>>> s.isspace()
True
>>> s=" "
>>> s.isspace()
True
22、str.istitle()
检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
>>> s="hello world"
>>> s.istitle()
False
>>> s="Hello world"
>>> s.istitle()
False
>>> s="Hello World"
>>> s.istitle()
True
23、str.isupper()
如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
>>> s="hello world"
>>> s.isupper()
False
>>> s="Hello World"
>>> s.isupper()
False
>>> s="HELLO"
>>> s.isupper()
True
24、str.join(iterable)
以 str作为分隔符,将 iterable中所有的元素(的字符串表示)合并为一个新的字符串
>>> s = ("hello","world")
>>> "-".join(s)
'hello-world'
25、str.ljust(width[, fillchar])
返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
>>> s="hello world"
>>> s.ljust(20,"*")
'hello world*********'
26、str.lower()
转换 string 中所有大写字符为小写.
>>> s="Hello World"
>>> s.lower()
'hello world'
27、str.lstrip([chars])
截掉 string 左边的空格
>>> s=" Hello World"
>>> s.lstrip()
'Hello World'
28、static str.maketrans(x[, y[, z]])
maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
原始字符串是"hello world",创建字符映射,e用1代替,l用2代替
>>> s="hello world"
>>> s_in = "el"
>>> s_out = "12"
>>> trantab = str.maketrans(s_in,s_out)
>>> s.translate(trantab)
'h122o wor2d'
29、str.partition(sep)
有点像 find()和 split()的结合体,从sep出现的第一个位置起,把 字 符 串 string 分 成 一 个 3 元 素 的 元 组 (string_pre_str,str,string_post_str),如果 string 中不包含str则 string_pre_str == string.
>>> s="hello world"
>>> s.partition("w")
('hello ', 'w', 'orld')
30、string.replace(str1, str2, num=string.count(str1))
把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次.
>>> s="hello world"
>>> s.replace("l","9")
'he99o wor9d'
>>> s.replace("l","9",2)
'he99o world'
31、str.rfind(sub[, start[, end]])
类似于 find() 函数,返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。
>>> s="hello world"
>>> s.rfind("w")
6
>>> s.rfind("k")
-1
32、str.rindex(sub[, start[, end]])
类似于 index(),不过是从右边开始.
>>> s="hello world"
>>> s.rindex("r")
8
33、str.rjust(width[, fillchar])
返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
>>> s="hello world"
>>> s.rjust(20,"*")
'*********hello world'
34、str.rpartition(sep)
类似于 partition()函数,不过是从右边开始查找
>>> s="hello world"
>>> s.rpartition("w")
('hello ', 'w', 'orld')
35、str.rsplit(sep=None, maxsplit=- 1)
>>> s="hello world"
>>> s.rsplit()
['hello', 'world']
>>> s.rsplit("w")
['hello ', 'orld']
36、str.rstrip([chars])
删除 string 字符串末尾的指定字符(默认为空格).
>>> s="hello world"
>>> s.rstrip()
'hello world'
>>> s.rstrip("d")
'hello worl'
37、string.split(str="", num=string.count(str))
以 str 为分隔符切片 string,如果 num 有指定值,则仅分隔 num+1 个子字符串
>>> s="hello world"
>>> s.split(" ")
['hello', 'world']
>>> s.split("l")
['he', '', 'o wor', 'd']
>>> s.split("w")
['hello ', 'orld']
38、str.splitlines([keepends])
按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
>>> s='ab c\n\nde fg\rkl\r\n'
>>> s.splitlines()
['ab c', '', 'de fg', 'kl']
>>> str2 = 'ab c\n\nde fg\rkl\r\n'
>>> str2.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
39、str.startswith(prefix[, start[, end]])
检查字符串是否是以 prefix开头,是则返回 True,否则返回 False。如果start 和 end 指定值,则在指定范围内检查.
>>> s="hello world"
>>> s.startswith("he")
True
>>> s.startswith("e")
False
40、str.strip([chars])
在 string 上执行 lstrip()和 rstrip()
>>> s=" hello world "
>>> s.strip()
'hello world'
41、str.swapcase()
翻转 string 中的大小写
>>> s="Hello World"
>>> s.swapcase()
'hELLO wORLD'
42、str.title()
返回"标题化"的 string,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
>>> s="hello world"
>>> s.title()
'Hello World'
43、str.translate(table)
根据 str 给出的表(包含 256 个字符)转换 string 的字符,要过滤掉的字符放到 del 参数中
>>> s="hello world"
>>> s_in = "el"
>>> s_out = "12"
>>> trantab = str.maketrans(s_in,s_out)
>>> s.translate(trantab)
'h122o wor2d'
44、str.upper()
转换 string 中的小写字母为大写
>>> s="hello world"
>>> s.upper()
'HELLO WORLD'
45、str.zfill(width)
返回长度为 width 的字符串,原字符串 string 右对齐,前面填充0
>>> s="hello world"
>>> s.zfill(20)
'000000000hello world'