列表可以进行增删改查,有下标,可切片;
字符串可以进行读取,由下表,可前片,但是不可修改;
特性:不可修改 ——所有看上去似乎是修改的attribute,比方capitalize(),upper(),lower()其实是改写为全新的内容,而不是在原字符串上进行修改。
下面介绍关于Python3.6版本中的字符串的所有可用的操作方法。




以上截图的所有attribute是我们可以调用的字符串的所有的方法。
具体的操作方法和使用方法如下:
1.S.capitalize() 首字母大写,其余字母小写
1 help(str.capitalize) 2 Help on method_descriptor: 3 4 capitalize(...) 5 S.capitalize() -> str 6 7 Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. #返回首字母大写,其余字母小写的字符串。 8 9 ‘this is a string'.capitalize() #首字母大写 10 Out[7]: 'This is a string'
2.S.casefold() 字母全部小写,适用于任何编码
1 help(str.casefold) 2 Help on method_descriptor: 3 4 casefold(...) 5 S.casefold() -> str 6 7 Return a version of S suitable for caseless comparisons. 8 #转换所有字母为小写模式; 9 #Python3.3中引入了str.casefold()方法,其效果和 string.lower()非常类似,都可以把字符串变成小写,那么它们之间有什么区别?他们各自的应用场景? 10 '''对 Unicode 的时候用 casefold() 11 Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold()converts it to "ss". 12 The casefolding algorithm is described in section 3.13 of the Unicode Standard 13 lower() 只对 ASCII 也就是 'A-Z'有效,但是其它一些语言里面存在小写的情况就没办法了。文档里面举得例子是德语中'ß'的小写是'ss': 14 s = 'ß' s.lower() # 'ß' s.casefold() # 'ss' 15 ''' 16 17 'aAAAAA'.casefold() 18 Out[4]: 'aaaaaa'
3.S.lower() 字母全部小写,仅适合ascii码
1 help(str.lower) 2 Help on method_descriptor: 3 4 lower(...) 5 S.lower() -> str 6 7 Return a copy of the string S converted to lowercase. 8 #返回小写的字符串副本 9 10 'AAa'.lower() 11 Out[6]: 'aaa'
4.S.upper() 字母全部大写
1 help(str.upper) 2 Help on built-in function upper: 3 4 upper(...) method of builtins.str instance 5 S.upper() -> str 6 7 Return a copy of S converted to uppercase. #返回字符串的副本,转换为大写字母的字符串。 8 9 'aABb'.upper() 10 Out[7]: 'AABB'
5.S.title() 字符串按标题格式转换,首字母大写,其余小写
1 help(str.title) 2 Help on built-in function title: 3 4 title(...) method of builtins.str instance 5 S.title() -> str 6 7 Return a titlecased version of S, i.e. words start with title case 8 characters, all remaining cased characters have lower case. #返回字符串的标题格式。首字母大写,其余小写。 9 10 'this is a string'.title() 11 Out[102]: 'This Is A String'
6.S.islower() 判断字符串的所有字符是否为小写
1 help(str.islower) 2 Help on built-in function islower: 3 4 islower(...) method of builtins.str instance 5 S.islower() -> bool 6 7 Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. #如果字符串的所有字符是小写字母则返回为True。 8 9 'aaaa'.islower() 10 Out[8]: True 11 12 'Aaaaa'.islower() 13 Out[9]: False
7.S.isupper() 判断字符串的所有字符是否为大写
1 help(str.isupper) 2 Help on built-in function isupper: 3 4 isupper(...) method of builtins.str instance 5 S.isupper() -> bool 6 7 Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. #如果字符串的所有字母都是大写的则返回True。 8 9 'AAAA'.isupper() 10 Out[10]: True 11 12 'AAAAa'.isupper() 13 Out[11]: False
8.S.istitle() 判断字符串格式是否为标题格式
1 help(str.istitle) 2 Help on built-in function istitle: 3 4 istitle(...) method of builtins.str instance 5 S.istitle() -> bool 6 7 Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. #如果字符串是标题格式则为True。 8 'this is a book'.istitle() 9 10 Out[12]: False 11 12 'this is a book'.title().istitle() 13 Out[13]: True
9.S.isalnum() 判断字符串内的字符是否都为字母或数字
1 help(str.isalnum) 2 Help on built-in function isalnum: 3 4 isalnum(...) method of builtins.str instance 5 S.isalnum() -> bool 6 7 Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. 8 #如果在字符串中的所有字符是字母数字的,返回为True;如果不是,则返回False。 9 10 '123tri'.isalnum() 11 Out[63]: True 12 13 'Tri123'.isalnum() 14 Out[65]: True
10.S.isalpha() 判断字符串内的字符是否都为字母
1 help(str.isalpha) 2 Help on built-in function isalpha: 3 4 isalpha(...) method of builtins.str instance 5 S.isalpha() -> bool 6 7 Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. #所有的字符串字符均为字母则返回为True;否则,返回False。 8 9 ’this is a book'.isalpha() #空格也是字符之一 10 Out[67]: False 11 12 'Aa'.isalpha() 13 Out[68]: True
11.S.isdecimal() 判断字符串是否为十进制
1 help(str.isdecimal) 2 Help on built-in function isdecimal: 3 4 isdecimal(...) method of builtins.str instance 5 S.isdecimal() -> bool 6 7 Return True if there are only decimal characters in S, False otherwise. #如果字符串中只有十进制字符,返回True。 8 9 ‘this is a book’.isdecimal() 10 Out[72]: False 11 12 '123'.isdecimal() 13 Out[73]: True 14 15 '0x123'.isdecimal() #16进制 16 Out[76]: False
12.S.isdigit() 判断字符串中字符是否都是数字
1 help(str.isdigit) 2 Help on built-in function isdigit: 3 4 isdigit(...) method of builtins.str instance 5 S.isdigit() -> bool 6 7 Return True if all characters in S are digits and there is at least one character in S, False otherwise. #如果在字符串中的所有字符都是数字则返回True 8 9 'this is a book'.isdigit() 10 Out[80]: False 11 12 '123'.isdigit() 13 Out[81]: True
13.S.isnumeric() 判断字符串中的字符是否都是数字
1 help(str.isnumeric) 2 Help on built-in function isnumeric: 3 4 isnumeric(...) method of builtins.str instance 5 S.isnumeric() -> bool 6 7 Return True if there are only numeric characters in S,False otherwise. #如果在字符串中仅有数字则返回True。 8 9 ‘this is a book’.isnumeric() 10 Out[98]: False 11 12 '123'.isnumeric() 13 Out[99]: True
上面的三个方法,str.isdigit(),str.sidecimal(),str.isnumeric()都是判断字符是否为数字,只是适用于不同的字符编码。
S.isnumeric()中小数也会返回false,因为小数点不是数字。

14.S.isidentifier() 判断字符串是不是一个合法的标识符
1 help(str.isidentifier) 2 Help on built-in function isidentifier: 3 4 isidentifier(...) method of builtins.str instance 5 S.isidentifier() -> bool 6 7 Return True if S is a valid identifier according to the language definition. #如果字符串是一个合法的标识符,返回True。 8 Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". 9 10 'def'.isidentifier() 11 Out[84]: True 12 13 'class'.isidentifier() 14 Out[85]: True 15 16 '123'.isidentifier() 17 Out[86]: False
所有符合合法的标识符格式的变量都会返回True;反之,123abc,-aa等不符合变量命名规则的都会返回False。
15.S.isprintable() 判断字符串是否都是可打印字符 如:tty file,drive file
1 help(str.isprintable) 2 Help on built-in function isprintable: 3 4 isprintable(...) method of builtins.str instance 5 S.isprintable() -> bool 6 7 Return True if all characters in S are considered printable in repr() or S is empty, False otherwise. #如果字符串中的所有字符为空或都是可以打印字符,则为True。 8 9 'this is a book'.isprintable() 10 Out[106]: True 11 12 '***'.isprintable() 13 Out[107]: True
16.S.isspace() 所有字符都是空白字符、\t、\n、\r
1 help(str.isspace) 2 Help on built-in function isspace: 3 4 isspace(...) method of builtins.str instance 5 S.isspace() -> bool 6 7 Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. #如果在字符串中的所有字符都是空白字符、\t、\n、\r,则返回True。 8 9 ' '.isspace() 10 Out[111]: True 11 12 ' 1'.isspace() 13 Out[112]: False 14 15 16 '\t \r \n'.isspace() 17 Out[20]: True
17.S.endswith() 判断字符串(或字符串子串)的结尾的字符是否符合指定的后缀
1 help(str.endswith) 2 Help on built-in function endswith: 3 4 endswith(...) method of builtins.str instance 5 S.endswith(suffix[, start[, end]]) -> bool 6 7 Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position.suffix can also be a tuple of strings to try. 8 9 10 str=''this is a string" 11 12 str.endswith('g') 13 Out[34]: True 14 15 str.endswith('g',1,8) #对str切片,判断子串是否以'g'为结尾。 16 Out[35]: False 17 18 str.endswith(('s','g')) #suffix can also be a tuple of strings to try.结果是只要元组中的其中之一为True,即为True。 19 Out[36]: True 20 21 str.endswith(('g','s')) 22 Out[37]: True
18.S.startswith() 判断字符串(或字符串子串)的开头的字符是否符合指定的前缀
1 help(str.startswith) 2 Help on built-in function startswith: 3 4 startswith(...) method of builtins.str instance 5 S.startswith(prefix[, start[, end]]) -> bool 6 7 Return True if S starts with the specified prefix, False otherwise. 8 With optional start, test S beginning at that position.With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. #如果字符串前缀是指定的prefix,返回True。 9 10 '11113333'.startswith('1') 11 Out[189]: True
19.S.find() 在字符串(或字符子串)中找到指定的字符的最小的下标;找不到,返回-1.
1 help(str.find) 2 Help on built-in function find: 3 4 find(...) method of builtins.str instance 5 S.find(sub[, start[, end]]) -> int #返回在字符串中或字符串子串中的最小的下标 6 7 Return the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. 8 Return -1 on failure. 9 10 11 'this is a string'.find('s') 12 Out[50]: 3
20.S.rfind() 在字符串(或字符子串)中找到指定的字符的最大的下标;找不到,返回-1.
1 help(str.rfind) 2 Help on built-in function rfind: 3 4 rfind(...) method of builtins.str instance 5 S.rfind(sub[, start[, end]]) -> int 6 7 Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. 8 Return -1 on failure. #返回在字符串中指定的子字符串出现的最大的下标。如果未找到输出“-1”。 9 10 '01234567890'.rfind('0') 11 Out[172]: 10 12 13 '01234567890'.rfind('0',0,10) 14 Out[173]: 0
21.S.index() 在字符串(或字符子串)中找到指定的字符的最小的下标;找不到,会报错
1 help(str.index) 2 Help on built-in function index: 3 4 index(...) method of builtins.str instance 5 S.index(sub[, start[, end]]) -> int 6 7 Like S.find() but raise ValueError when the substring is not found.#如果未找到子串,则会报错;如果找到子串,则返回子串的最小的下标 8 9 'this is a string'.index('s') 10 Out[56]: 3 11 12 'this is a string'.index('S') 13 Traceback (most recent call last): 14 15 File "<ipython-input-57-671a49dcd72c>", line 1, in <module> 16 str.index('S') 17 18 ValueError: substring not found 19 20 'this is a string'.index('string') 21 Out[59]: 10
22.S.rindex() 在字符串(或字符子串)中找到指定的字符的最大的下标 ;找不到,会报错
1 help(str.rindex) 2 Help on built-in function rindex: 3 4 rindex(...) method of builtins.str instance 5 S.rindex(sub[, start[, end]]) -> int 6 7 Like S.rfind() but raise ValueError when the substring is not found. #如果子字符串没有在字符串中找到,会报错。除此之外和S.rfind()功能一样。但是S.rfind()找不到时返回的是-1. 8 9 'this is a string'.rindex('s') 10 Out[21]: 10 11 12 'this is a string'.rindex('s',0,9) 13 Out[22]: 6
23.S.center() 字符串居中,指定长度的两边根据指定的字符填充(默认为空格)
1 help(str.center) 2 Help on method_descriptor: 3 4 center(...) 5 S.center(width[, fillchar]) -> str 6 7 Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) 8 9 ’this is a string'.center(50) 10 Out[12]: ' this is a string ' 11 12 'this is a string'.center(50,'---') 13 Traceback (most recent call last): 14 15 File "<ipython-input-13-a1b9271e33e1>", line 1, in <module> 16 str.center(50,'---') 17 18 TypeError: The fill character must be exactly one character long 19 20 21 'this is a string'.center(50,'-') #str.center(self,width,fillchar) 返回字符串宽度(即长度)为50的字符串,字符串内容居中,两边缺少的以fillchar填充两边,如无具体指定值,默认为“”(空格)。 22 Out[14]: '-----------------this is a string-----------------'
24.S.ljust() 返回字符串指定长度的字符串,其中原字符串的字符在左侧,添加的指定填充字符在右边(默认指定空格)。
1 help(str.ljust) 2 Help on built-in function ljust: 3 4 ljust(...) method of builtins.str instance 5 S.ljust(width[, fillchar]) -> str 6 7 Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). #返回字符串指定长度的字符串,其中原字符串的字符在左侧,添加的指定填充字符在右边(默认指定空格)。 8 9 ‘this is a string'.ljust(30,'-') 10 Out[128]: 'this is a string--------------'
25.S.rjust() 返回字符串指定长度的字符串,其中原字符串的字符在右侧,添加的指定填充字符在左边(默认指定空格)。
1 help(str.rjust) 2 Help on built-in function rjust: 3 4 rjust(...) method of builtins.str instance 5 S.rjust(width[, fillchar]) -> str 6 7 Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space).#返回字符串指定长度的字符串,其中原字符串的字符在右侧,添加的指定填充字符在左边(默认指定空格)。 8 9 str.rjust(30,'-') 10 Out[129]: '--------------this is a string'
26.S.strip() 返回移除字符串头尾指定的字符生成的新字符串
1 help(str.strip) 2 Help on built-in function strip: 3 4 strip(...) method of builtins.str instance 5 S.strip([chars]) -> str 6 7 Return a copy of the string S with leading and trailing whitespace removed.If chars is given and not None, remove characters in chars instead. #返回移除字符串头尾指定的字符生成的新字符串。 8 9 ' 123 '.strip() #去除两侧的空格 10 Out[135]: '123' 11 12 ' 1 2 3 '.strip() #去除两侧的空格 13 Out[136]: '1 2 3' 14 15 16 '\t \n \r 123 456 \t \n\r'.strip() #去除两侧的空白字符、\n,\t,\r 17 Out[24]: '123 456' 18 19 '0000 123 000'.strip('0') #去除指定的参数'0' 20 Out[25]: ' 123 '
27.S.lstrip() 返回移除字符串左侧指定的字符生成的新字符串
1 help(str.lstrip) 2 Help on built-in function lstrip: 3 4 lstrip(...) method of builtins.str instance 5 S.lstrip([chars]) -> str 6 7 Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead.#返回去除了字符串左边(领先的)空格的字符串的副本。 8 9 '0000 123 4 000'.lstrip('0') 10 Out[26]: ' 123 4 000' 11 12 '\n \t \r 123 455 \n \t\r'.lstrip() 13 Out[27]: '123 455 \n \t\r'
28.S.rstrip() 返回移除字符串右侧指定的字符生成的新字符串
1 help(str.rstrip) 2 Help on built-in function rstrip: 3 4 rstrip(...) method of builtins.str instance 5 S.rstrip([chars]) -> str 6 7 Return a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead. #返回去除了字符串右边(尾部的)空格的字符串的副本。 8 9 '\n \t \r 123 455 \n \t\r'.rstrip() 10 Out[28]: '\n \t \r 123 455' 11 12 '0000 123 000'.rstrip('0') 13 Out[29]: '0000 123 '
29.S.split() 返回的是一个行的列表,默认是空白字符作为分隔符,也可以指定分隔的个数(即分隔符的个数),从左往右
1 help(str.split) 2 Help on built-in function split: 3 4 split(...) method of builtins.str instance 5 S.split(sep=None, maxsplit=-1) -> list of strings 6 7 Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.#返回在字符串中的单词列表,使用sep的值作为分隔符。如果最大的分隔数给定了,最多最大分隔数已经完成。 8 如果sep没有指定特别的,或者没有指定分隔符,那么默认空格为分隔符,并且将字符串中的空白字符串从结果中删除。 9 10 '1 22 3 3 4 . 6'.split(sep="3",maxsplit=1) #分隔符一定是字符串格式,另外设置了maxsplit为1个,导致输出结果仅用了最前面的“3”作为分隔符 11 Out[163]: ['1 22 ', ' 3 4 . 6'] 12 13 '1 22 3 3 4 . 6'.split(sep="3") #使用默认的maxsplit值,两个“3“都作为分隔符处理完了。 14 Out[166]: ['1 22 ', ' ', ' 4 . 6'] 15 16 #str.split()和str.rsplit()的区别在于取指定的分隔符进行分列时,从前向右,还是从右(尾)向前的执行选择顺序。
30.S.rsplit() 返回的是一个行的列表,默认是空白字符作为分隔符,也可以指定分隔的个数(即分隔符的个数),从右向左
1 help(str.rsplit) 2 Help on built-in function rsplit: 3 4 rsplit(...) method of builtins.str instance 5 S.rsplit(sep=None, maxsplit=-1) -> list of strings 6 7 Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. #同上,只是是从字符串的末尾开始,运行至最前面。 8 9 '1 22 3 3 4 . 6'.rsplit(sep="3",maxsplit=1) #分隔符一定是字符串格式,另外设置了maxsplit为1个,导致输出结果仅用了最后面的“3”作为分隔符 10 Out[164]: ['1 22 3 ', ' 4 . 6'] 11 12 '1 22 3 3 4 . 6'.rsplit(sep="3") #使用默认的maxsplit值,两个“3“都作为分隔符处理完了。 13 Out[165]: ['1 22 ', ' ', ' 4 . 6'] 14 15 'this is a string'.rsplit(sep=' ',maxsplit=2) 16 Out[33]: ['this is', 'a', 'string']
31.S.splitlines() 返回的是一个行的列表,根据换行符进行拆分
1 help(str.splitlines) 2 Help on built-in function splitlines: 3 4 splitlines(...) method of builtins.str instance 5 S.splitlines([keepends]) -> list of strings 6 7 Return a list of the lines in S, breaking at line boundaries.Line breaks are not included in the resulting list unless keepends is given and true. #返回字符串列表,在边界出打破,边界指的是\n新行,\r换行。分隔行不会在返回结果的列表中出现,除非keepends=True。 8 9 '123 \n '.splitlines() 10 Out[185]: ['123 ', ' '] #针对的是\n,\r这样指定的换行符。 11 12 'this is a string \n hello word'.splitlines(2) 13 Out[40]: ['this is a string \n', ' hello word']
32.S.format() 返回一个格式化的字符串,使用后面的参数对前面进行替换。替换参数通过{}来标识。可以用下标,“=”,下标对应等方式映射。
1 help(str.format) 2 Help on built-in function format: 3 4 format(...) method of builtins.str instance 5 S.format(*args, **kwargs) -> str 6 7 Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). 8 #返回一个格式化的字符串,使用后面的参数对前面进行替换。替换参数通过{}来标识。 9 10 'I am a {sex}.'.format(sex='girl') 11 Out[52]: 'I am a girl.'
33.S.format_map() 返回一个格式化的字符串,使用后面的参数对前面进行替换。替换参数通过{}来标识。必须用字典形式表示。
1 help(str.format_map) 2 Help on built-in function format_map: 3 4 format_map(...) method of builtins.str instance 5 S.format_map(mapping) -> str 6 7 Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). 8 9 'I am a {sex}.I am {age} years old.'.format_map({'sex':'girl','age':18}) #用S.format_map的字典映射的方式替换 10 Out[54]: 'I am a girl.I am 18 years old.'
34.S.count() 返回的数量范围内出现的子串子[开始,结束]。片符号被解释为可选参数的开始和结束。
1 help(str.count) 2 Help on built-in function count: 3 4 count(...) method of builtins.str instance 5 S.count(sub[, start[, end]]) -> int 6 7 Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. #返回字符串(切片的子串)中的非重叠出现的次数 8 9 str.count('s') 10 Out[17]: 3 11 12 str.count('s',4,) 13 Out[18]: 2
35.S.join() 将序列中的元素以指定的字符连接生成一个新的字符串。指定的字符.join('字符串')
1 help(str.join) 2 Help on built-in function join: 3 4 join(...) method of builtins.str instance 5 S.join(iterable) -> str 6 7 Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. #用str字符串作为分隔符,将传入的iterable(可迭代对象)分隔开来。 8 9 str.join('123') #用S填充在1,2,3之间 10 Out[114]: '1this is a string2this is a string3' 11 12 str.join('*') #“*”不可迭代,所以无效 13 Out[115]: '*' 14 15 str.join('==') #str作为分隔符,将“==”可迭代对象进行分隔。 16 Out[119]: '=this is a string=' 17 18 '+'.join(str) 19 Out[120]: 't+h+i+s+ +i+s+ +a+ +s+t+r+i+n+g' 20 21 '+'.join('123456789') 22 Out[121]: '1+2+3+4+5+6+7+8+9' 23 24 #故,前面是 分隔符.join(iterable)
36.S.replace() 将字符串中的指定的旧字符更改为新字符,可以限定替换的个数
1 help(str.replace) 2 Help on built-in function replace: 3 4 replace(...) method of builtins.str instance 5 S.replace(old, new[, count]) -> str 6 7 Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. #返回所有旧子字符串被新的子字符串替换的字符串的副本。如果可选参数count给定了具体值,仅仅替换给定的count的前几个出现的值。 8 9 '11111'.replace("1","2",2) 10 Out[170]: '22111'
37.S.encode() 对字符串按照指定编码进行编码,解码
1 help(str.encode) 2 Help on built-in function encode: 3 4 encode(...) method of builtins.str instance 5 S.encode(encoding='utf-8', errors='strict') -> bytes 6 7 Encode S using the codec registered for encoding. Default encoding 8 is 'utf-8'. errors may be given to set a different error 9 handling scheme. Default is 'strict' meaning that encoding errors raise 10 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 11 'xmlcharrefreplace' as well as any other name registered with 12 codecs.register_error that can handle UnicodeEncodeErrors. 13 14 'this is a string'.encode(encoding='ASCII',errors='strict') #对str向ascii码进行编码; 15 Out[22]: b'this is a string' 16 17 'this is a string'.encode(encoding='ASCII',errors='strict').decode('utf-8') 18 #对二进制进行解码 19 Out[25]: 'this is a string'
38.S.swapcase() 大小写字母切换,大写变小写,小写变大写
1 help(str.swapcase) 2 Help on built-in function swapcase: 3 4 swapcase(...) method of builtins.str instance 5 S.swapcase() -> str 6 7 Return a copy of S with uppercase characters converted to lowercase and vice versa. #返回字符串转换完成的副本,大小字符转换为小写字母,小写字母转换为大写字母。 8 9 'aA'.swapcase() 10 Out[192]: 'Aa'
39.S.expandtabs() 返回在制表符,即通过空格进行了扩展字符串,' '的副本。
1 help(str.expandtabs) 2 Help on built-in function expandtabs: 3 4 expandtabs(...) method of builtins.str instance 5 S.expandtabs(tabsize=8) -> str 6 7 Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. 8 9 10 'this is a string'.expandtabs(tabsize=50) #由于str中没有制表符,所以没有起到作用。 11 Out[39]: 'this is a string' 12 13 'a\t'.expandtabs(tabsize=50) #仅对制表符tab characters起到作用。最终结果是字符串加上空格键=50 14 Out[41]: 'a '
40.S.maketrans()
- 用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,
- 第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
- 注:两个字符串的长度必须相同,为一一对应的关系。
1 help(str.maketrans) 2 Help on built-in function maketrans: 3 4 maketrans(x, y=None, z=None, /) 5 Return a translation table usable for str.translate(). 6 7 If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. 8 #如果仅有一个参数,那么这个参数必须是一个字典映射的序列(整数),字符序列或字符串。字符的键必须被转换成序列。 9 If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. #如果有两个参数,他们必须是两个等长的,并且在返回结果的字典中是一一对应的关系。参数x上的每个字符将会对应在相同的下标位上的参数y的字符。 10 If there is a third argument, it must be a string, whose characters will be mapped to None in the result. #如果有三个参数,参数必须是一个字符串,其字符在结果中会映射到None。 11 12 intab='aeiou' 13 14 outtab='12345' 15 16 str_trantab=str.maketrans(intab,outtab) 17 18 test_str='csdn blog:http://blog.csdn.net/wirelessqa' 19 20 print(test_str.translate(str_trantab)) 21 csdn bl4g:http://bl4g.csdn.n2t/w3r2l2ssq1 22 23 #可以用于暗码的,无解,仅能够通过得知源代码才能解析出原来的字符串的结果。
41.S.translate() 根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。
1 help(str.maketrans) 2 Help on built-in function maketrans: 3 4 maketrans(x, y=None, z=None, /) 5 Return a translation table usable for str.translate(). 6 7 If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. 8 #如果仅有一个参数,那么这个参数必须是一个字典映射的序列(整数),字符序列或字符串。字符的键必须被转换成序列。 9 If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. 10 #如果有两个参数,他们必须是两个等长的,并且在返回结果的字典中是一一对应的关系。参数x上的每个字符将会对应在相同的下标位上的参数y的字符。 11 If there is a third argument, it must be a string, whose characters will be mapped to None in the result. 12 #如果有三个参数,参数必须是一个字符串,其字符在结果中会映射到None。 13 14 intab='aeiou' 15 16 outtab='12345' 17 18 str_trantab=str.maketrans(intab,outtab) 19 20 test_str='csdn blog:http://blog.csdn.net/wirelessqa' 21 22 print(test_str.translate(str_trantab)) 23 csdn bl4g:http://bl4g.csdn.n2t/w3r2l2ssq1 24 25 #可以用于暗码的,无解,仅能够通过得知源代码才能解析出原来的字符串的结果。
语法
translate()方法语法:str.translate(table[, deletechars]);
参数:table -- 翻译表,翻译表是通过maketrans方法转换而来。
deletechars -- 字符串中要过滤的字符列表。
返回值:返回翻译后的字符串。
42.S.zfill() 指定字符串长度,填充0到字符串的左边。
1 help(str.zfill) 2 Help on built-in function zfill: 3 4 zfill(...) method of builtins.str instance 5 S.zfill(width) -> str 6 7 Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.#在左侧填充0,以填充指定宽度的字段。字符串永远不会被截断。 8 9 'this is a string'.zfill(30) 10 Out[43]: '00000000000000this is a string'
43.S.partition() 指定分隔符,在字符串中查找分隔符,返回分隔符之前的部分,分隔符本身和分隔符之后的部分。结果为一个元组。从左向右开始,仅将最小下标的指定分隔符作为分隔符。
1 help(str.partition) 2 Help on built-in function partition: 3 4 partition(...) method of builtins.str instance 5 S.partition(sep) -> (head, sep, tail) 6 7 Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. #在字符串中查找分隔符,返回分隔符之前的部分,分隔符本身和分隔符之后的部分。如果分隔符没有找到,返回字符串本身和两个空的字符串。 8 9 "my name is {}, and age is {}".partition('is') 10 Out[178]: ('my name ', 'is', ' {}, and age is {}') 11 #分隔符之前的部分,分隔符本身,分隔符之后的部分。 12 #从前往后,选中第一个is作为分隔符
44.S.rpartition() 指定分隔符,在字符串中查找分隔符,返回分隔符之前的部分,分隔符本身和分隔符之后的部分。结果为一个元组。从右向左开始,仅将最大下标的指定分隔符作为分隔符。
1 help(str.rpartition) 2 Help on built-in function rpartition: 3 4 rpartition(...) method of builtins.str instance 5 S.rpartition(sep) -> (head, sep, tail) 6 7 Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. 8 #在字符串中查找分隔符,在字符串的最后开始,返回分隔符之前的部分,分隔符本身和分隔符之后的部分。如果分隔符没有找到,返回两个空的字符串和字符串本身。 9 10 "my name is {}, and age is {}".rpartition('is') 11 Out[179]: ('my name is {}, and age ', 'is', ' {}') 12 #分隔符之前的部分,分隔符本身,分隔符之后的部分。 13 #从后往前,选中第一个is作为分隔符
浙公网安备 33010602011771号