Python提供了许多可用于字符串的内置方法。
以下是Python 3中可用的字符串方法的列表。
方法 | 描述 | 例子 |
大写() | 返回字符串的副本,该字符串的首字符大写,其余小写。 | >>> mystring = "hello python" >>> print(mystring.capitalize()) Hello python |
Casefold() | 返回该字符串的casefolded副本。折叠的字符串可用于无大小写的匹配。 | >>> mystring = "hello PYTHON" >>> print(mystring.casefold()) hello python |
中心(宽度,[填充字符]) | 返回以长度width的字符串为中心的字符串。可以使用指定的fillchar进行填充(默认填充使用ASCII空间)。如果width小于或等于len,则返回原始字符串 | >>> mystring = "Hello" >>> x = mystring.center(12, "-") >>> print(x) ---Hello---- |
计数(子,[开始],[结束]) | 返回[ start,end ]范围内子字符串(sub)的不重叠出现次数。可选参数start和end解释为切片表示法。 | >>> mystr = "Hello Python" >>> print(mystr.count("o")) 2 >>> print(mystr.count("th")) 1 >>> print(mystr.count("l")) 2 >>> print(mystr.count("h")) 1 >>> print(mystr.count("H")) 1 >>> print(mystr.count("hH")) 0 |
编码(编码=“ utf-g”,错误=“严格”) | 以字节对象的形式返回字符串的编码版本。默认编码为utf-8。可以设置错误以设置不同的错误处理方案。错误的可能值为:
| >>> mystr = 'python!' >>> print('The string is:', mystr) The string is: python! >>> print('The encoded version is: ', mystr.encode("ascii", "ignore")) The encoded version is: b'python!' >>> print('The encoded version (with replace) is:', mystr.encode("ascii", "replace")) The encoded version (with replace) is: b'python!' |
endwith(后缀,[开始],[结束]) | 如果字符串以指定的后缀结尾,则返回True,否则返回False。 | >>> mystr = "Python" >>> print(mystr.endswith("y")) False >>> print(mystr.endswith("hon")) True |
Expandtabs(tabsize = 8) | 返回字符串的副本,其中所有制表符都被一个或多个空格替换,具体取决于当前列和给定的制表符大小。 | >>> mystr = "1\t2\t3" >>> print(mystr) 1 2 3 >>> print(mystr.expandtabs()) 1 2 3 >>> print(mystr.expandtabs(tabsi ze=15)) 1 2 3 >>> print(mystr.expandtabs(tabsi ze=2)) 1 2 3 |
查找(子,[开始],[结束]) | 返回在切片s [start:end]中找到子字符串sub的字符串中的最低索引。 | >>> mystring = "Python" >>> print(mystring.find("P")) 0 >>> print(mystring.find("on")) 4 |
格式(* args,** kwargs) | 执行字符串格式化操作。调用此方法的字符串可以包含文字文本或用大括号{}分隔的替换字段。 | >>> print("{} and {}".format("Apple", "Banana")) Apple and Banana >>> print("{1} and {0}".format("Apple", "Banana")) Banana and Apple >>> print("{lunch} and {dinner}".format(lunch="Peas ", dinner="Beans")) Peas and Beans |
format_map(映射) | 与format(** mapping)相似,除了直接使用映射而不将其复制到字典外。 | >>> lunch = {"Food": "Pizza", "Drink": "Wine"} >>> print("Lunch: {Food}, {Drink}".format_map(lunch)) Lunch: Pizza, Wine >>> class Default(dict): def __missing__(self, key): return key >>> lunch = {"Drink": "Wine"} >>> print("Lunch: {Food}, {Drink}".format_map(Default( lunch))) Lunch: Food, Wine |
索引(子,[开始],[结束]) | 在字符串中搜索指定的值,并返回找到该字符串的位置 | >>> mystr = "HelloPython" >>> print(mystr.index("P")) 5 >>> print(mystr.index("hon")) 8 >>> print(mystr.index("o")) 4 |
Isalnum | 如果字符串中的所有字符都是字母数字,则返回True | >>> mystr = "HelloPython" >>> print(mystr.isalnum()) True >>> a = "123" >>> print(a.isalnum()) True >>> a= "$*%!!!" >>> print(a.isalnum()) False |
Isalpha() | 如果字符串中的所有字符都在字母中,则返回True | >>> mystr = "HelloPython" >>> print(mystr.isalpha()) True >>> a = "123" >>> print(a.isalpha()) False >>> a= "$*%!!!" >>> print(a.isalpha()) False |
Isdecimal() | 如果字符串中的所有字符均为小数,则返回True | >>> mystr = "HelloPython" >>> print(mystr.isdecimal()) False >>> a="1.23" >>> print(a.isdecimal()) False >>> c = u"\u00B2" >>> print(c.isdecimal()) False >>> c="133" >>> print(c.isdecimal()) True |
Isdigit() | 如果字符串中的所有字符都是数字,则返回True | >>> c="133" >>> print(c.isdigit()) True >>> c = u"\u00B2" >>> print(c.isdigit()) True >>> a="1.23" >>> print(a.isdigit()) False |
isidentifier() | 如果字符串是标识符,则返回True | >>> c="133" >>> print(c.isidentifier()) False >>> c="_user_123" >>> print(c.isidentifier()) True >>> c="Python" >>> print(c.isidentifier()) True |
Islower() | 如果字符串中的所有字符均为小写,则返回True | >>> c="Python" >>> print(c.islower()) False >>> c="_user_123" >>> print(c.islower()) True >>> print(c.islower()) False |
Isnumeric() | 如果字符串中的所有字符均为数字,则返回True | >>> c="133" >>> print(c.isnumeric()) True >>> c="_user_123" >>> print(c.isnumeric()) False >>> c="Python" >>> print(c.isnumeric()) False |
isprintable() | 如果字符串中的所有字符都是可打印的,则返回True | >>> c="133" >>> print(c.isprintable()) True >>> c="_user_123" >>> print(c.isprintable()) True >>> c="\t" >>> print(c.isprintable()) False |
isspace() | 如果字符串中的所有字符都是空格,则返回True | >>> c="133" >>> print(c.isspace()) False >>> c="Hello Python" >>> print(c.isspace()) False 73 >>> c="Hello" >>> print(c.isspace()) False >>> c="\t" >>> print(c.isspace()) True |
istitle() | 如果字符串遵循标题规则,则返回True | >>> c="133" >>> print(c.istitle()) False >>> c="Python" >>> print(c.istitle()) True >>> c="\t" >>> print(c.istitle()) False |
isupper() | 如果字符串中的所有字符均为大写,则返回True | >>> c="Python" >>> print(c.isupper()) False >>> c="PYHTON" >>> print(c.isupper()) True >>> c="\t" >>> print(c.isupper()) False |
加入(可迭代) | 将可迭代的元素连接到字符串的末尾 | >>> a ="-" >>> print(a.join("123")) 1-2-3 >>> a="Hello Python" >>> a="**" >>> print(a.join("Hello Python")) H**e**l**l**o** **P**y**t**h**o**n |
ljust(width [,fillchar ]) | 返回字符串的左对齐版本 | >>> a="Hello" >>> b = a.ljust(12, "_") >>> print(b) Hello_______ |
降低() | 将字符串转换为小写 | >>> a = "Python" >>> print(a.lower()) Python |
lstrip([ chars ]) | 返回字符串的左修剪版本 | >>> a = " Hello " >>> print(a.lstrip(), "!") Hello |
maketrans(x [, y [, z ]]) | 返回要在翻译中使用的翻译表 | >>> frm = "SecretCode" >>> to = "4203040540" >>> trans_table = str.maketrans(frm,to) >>> sec_code = "Secret Code".translate(trans_table) >>> print(sec_code) 400304 0540 |
分区(sep) | 返回一个将字符串分为三部分的元组 | >>> mystr = "Hello-Python" >>> print(mystr.partition("- ")) ('Hello', '-', 'Python') 74 >>> print(mystr.partition(".")) ('Hello-Python', '', '') |
replace(old, new [,count ]) | 返回一个字符串,其中将指定值替换为指定值 | >>> mystr = "Hello Python. Hello Java. Hello C++." >>> print(mystr.replace("Hello", "Bye")) Bye Python. Bye Java. Bye C++. >>> print(mystr.replace("Hello", "Hell", 2)) Hell Python. Hell Java. Hello C++. |
rfind(sub [, start [,end ]]) | 在字符串中搜索指定的值,并返回找到它的最后位置 | >>> mystr = "Hello-Python" >>> print(mystr.rfind("P")) 6 >>> print(mystr.rfind("-")) 5 >>> print(mystr.rfind("z")) -1 |
rindex(sub [, start [,end ]]) | 在字符串中搜索指定的值,并返回找到它的最后位置 | >>> mystr = "Hello-Python" >>> print(mystr.rindex("P")) 6 >>> print(mystr.rindex("-")) 5 >>> print(mystr.rindex("z")) Traceback (most recent call last): File "<pyshell#253>", line 1, in <module> print(mystr.rindex("z")) ValueError: substring not found |
调整(width [,fillchar ]) | 返回字符串长度的字符串右对齐宽度。 | >>> mystr = "Hello Python" >>> mystr1 = mystr.rjust(20, "-") >>> print(mystr1) --------Hello Python |
rpartition(sep) | 返回一个将字符串分为三部分的元组 | >>> mystr = "Hello Python" >>> print(mystr.rpartition(".")) ('', '', 'Hello Python') >>> print(mystr.rpartition(" ")) ('Hello', ' ', 'Python') |
rsplit(sep =无,maxsplit = -1) | 在指定的分隔符处分割字符串,并返回一个列表 | >>> mystr = "Hello Python" >>> print(mystr.rsplit()) ['Hello', 'Python'] >>> mystr = "Hello-Python- Hello" >>> print(mystr.rsplit(sep="-", maxsplit=1)) ['Hello-Python', 'Hello'] |
rstrip([ chars ]) | 返回字符串的右修剪版本 | >>> mystr = "Hello Python" >>> print(mystr.rstrip(), "!") Hello Python ! >>> mystr = "------------ Hello Python-----------" >>> print(mystr.rstrip(), "- ") ------------Hello Python---- ------- - >>> print(mystr.rstrip(), "_") ------------Hello Python---- ------- _ |
分割(sep = None,maxsplit = -1) | 在指定的分隔符处分割字符串,并返回一个列表 | >>> mystr = "Hello Python" >>> print(mystr.split()) ['Hello', 'Python'] >>> mystr1="Hello,,Python" >>> print(mystr1.split(",")) ['Hello', '', 'Python'] |
分割线([keepends]) | 在换行符处分割字符串并返回一个列表 | >>> mystr = "Hello:\n\n Python\r\nJava\nC++\n" >>> print(mystr.splitlines()) ['Hello:', '', ' Python', 'Java', 'C++'] >>> print(mystr.splitlines(keepe nds=True)) ['Hello:\n', '\n', ' Python\r\n', 'Java\n', 'C++\n'] |
startswith(前缀[,开始[, 结束]]) | 如果字符串以指定值开头,则返回true | >>> mystr = "Hello Python" >>> print(mystr.startswith("P")) False >>> print(mystr.startswith("H")) True >>> print(mystr.startswith("Hell ")) True |
带([ chars ]) | 返回字符串的修剪版本 | >>> mystr = " Hello Python " >>> print(mystr.strip(), "!") Hello Python ! >>> print(mystr.strip(), " ") Hello Python |
swapcase() | 交换大小写,小写变成大写,反之亦然 | >>> mystr = "Hello PYthon" >>> print(mystr.swapcase()) hELLO python |
标题() | 将每个单词的第一个字符转换为大写 | >>> mystr = "Hello PYthon" >>> print(mystr.title()) Hello Python >>> mystr = "HELLO JAVA" >>> print(mystr.title()) Hello Java |
翻译(表) | 返回翻译后的字符串 | >>> frm = "helloPython" >>> to = "40250666333" >>> trans_table = str.maketrans(frm, to) >>> secret_code = "Secret Code".translate(trans_table) >>> print(secret_code) S0cr06 C3d0 |
上() | 将字符串转换为大写 | >>> mystr = "hello Python" >>> print(mystr.upper()) HELLO PYTHON |
zfill(宽度) | 以指定数量的0开头的字符串填充字符串 | >>> mystr = "999" >>> print(mystr.zfill(9)) 000000999 >>> mystr = "-40" >>> print(mystr.zfill(5)) -0040 |