Python 字符串方法?

pythonserver side programmingprogramming更新于 2025/5/12 8:44:17

Python 提供了许多可用于字符串的内置方法。

以下是 Python 3 中可用的字符串方法列表。

方法
描述
示例
capitalize()
返回字符串的副本,其中第一个字符大写,其余字符保留小写。
>>> mystring = "hello python"
>>> print(mystring.capitalize())
Hello python
Casefold()
返回字符串的大小写折叠副本。大小写折叠字符串可用于不大小写匹配。
>>> mystring = "hello PYTHON"
>>> print(mystring.casefold())
hello python
Center(width, [fillchar])
返回长度为 width 的字符串中居中的字符串。可以使用指定的 fillchar 进行填充(默认填充使用 ASCII 空格)。如果 width 小于或等于 len(s),则返回原始字符串
>>> mystring = "Hello"
>>> x = mystring.center(12,
"-")
>>> print(x)
---Hello----
Count(sub, [start], [end])
返回范围 [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
Encode(encoding = “utf-g”, errors = “strict”)
以字节对象形式返回字符串的编码版本。默认编码为 utf-8。可以指定错误以设置不同的错误处理方案。错误的可能值为:
  • strict (编码错误引发 UnicodeError)

  • ignore

  • replace

  • xmlcharrefreplace

  • backslashreplace

  • 通过 codecs.register_error() 注册的任何其他名称

 
>>> 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!'
endswith(suffix, [start], [end])
如果字符串以指定的后缀结尾,则返回 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
Find(sub, [start], [end])
返回在切片 s[start:end] 中找到子字符串 sub 的字符串中的最低索引。
>>> mystring = "Python"
>>>
print(mystring.find("P"))
0
>>>
print(mystring.find("on"))
4
Format(*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(mapping)
与 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
Index(sub, [start], [end])
在字符串中搜索指定值并返回找到该值的位置
>>> 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
join(iterable)
将可迭代对象的元素连接到字符串的末尾
>>> 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_______
lower()
将字符串转换为小写
>>> 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
partition(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
rjust(width[,fillchar])
返回长度为 width 的字符串中右对齐的字符串。
>>> 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=None, 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----
------- _
split(sep=None, maxsplit=-1)
在指定的分隔符处拆分字符串,并返回列表
>>> mystr = "Hello Python"
>>> print(mystr.split())
['Hello', 'Python']
>>> mystr1="Hello,,Python"
>>> print(mystr1.split(","))
['Hello', '', 'Python']
splitlines([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(prefix[,start[, end]])
如果字符串以指定值开头,则返回 true
>>> mystr = "Hello Python"
>>>
print(mystr.startswith("P"))
False
>>>
print(mystr.startswith("H"))
True
>>>
print(mystr.startswith("Hell
"))
True
strip([chars])
返回字符串的修剪版本
>>> mystr = "
Hello Python
"
>>> print(mystr.strip(),
"!")
Hello Python !
>>> print(mystr.strip(), "
")
Hello Python
swapcase()
交换大小写,小写变为大写,反之亦然
>>> mystr = "Hello PYthon"
>>> print(mystr.swapcase())
hELLO python
title()
将每个单词的第一个字符转换为大写
>>> mystr = "Hello PYthon"
>>> print(mystr.title())
Hello Python
>>> mystr = "HELLO JAVA"
>>> print(mystr.title())
Hello Java
translate(table)
返回翻译后的字符串
>>> frm = "helloPython"
>>> to = "40250666333"
>>> trans_table =
str.maketrans(frm, to)
>>> secret_code = "Secret
Code".translate(trans_table)
>>> print(secret_code)
S0cr06 C3d0
upper()
将字符串转换为大写
>>> mystr = "hello Python"
>>> print(mystr.upper())
HELLO PYTHON
zfill(width)
在开头用指定数量的 0 值填充字符串
>>> mystr = "999"
>>> print(mystr.zfill(9))
000000999
>>> mystr = "-40"
>>> print(mystr.zfill(5))
-0040

相关文章


有用资源