Skip to content

Python String API

Python str 方法,用于操作文本 —— 分割、替换、搜索、格式化和转换字符串。

1 class · 10 methods

str

10 methods

内置字符串类型。Unicode 码点的不可变序列。

str.split(sep=None, maxsplit=-1)

返回按 sep 分割的子字符串列表。如果 sep 为 None,则按任意空白字符分割并丢弃空字符串。

Parameters

NameTypeDescription
sepstr | None用于分割的分隔符。None 表示按空白字符分割。
maxsplitint最大分割次数(-1 表示无限制)。

Returns

list[str]

Example

python
'a,b,c'.split(',')        # ['a', 'b', 'c']
'  hello world  '.split()  # ['hello', 'world']
'a-b-c'.split('-', 1)     # ['a', 'b-c']
str.replace(old, new, count=-1)

返回将所有出现的子字符串 old 替换为 new 后的副本。

Parameters

NameTypeDescription
oldstr要替换的子字符串。
newstr替换后的字符串。
countint最大替换次数(-1 表示全部替换)。

Returns

str

Example

python
'hello world'.replace('world', 'Python')  # 'hello Python'
'a-b-c'.replace('-', '_', 1)              # 'a_b-c'
str.find(sub[, start[, end]])

返回找到 sub 的最低索引,未找到则返回 -1。不会抛出异常。

Parameters

NameTypeDescription
substr要查找的子字符串。
startint起始索引(包含)。
endint结束索引(不包含)。

Returns

int

Example

python
'hello world'.find('world')  # 6
'hello'.find('z')            # -1
'abcabc'.find('a', 1)        # 3
str.format(*args, **kwargs)

使用替换字段 {0}、{name} 等格式化字符串。f-strings 的前身。

Parameters

NameTypeDescription
*argsAny用于编号字段的位置参数。
**kwargsAny用于命名字段的关键字参数。

Returns

str

Example

python
'{} {}'.format('a', 'b')            # 'a b'
'{name}={value}'.format(name='x', value=10)  # 'x=10'
'{0:.2f}'.format(3.14159)                    # '3.14'
str.join(iterable)

使用该字符串作为分隔符,将 iterable 中的字符串连接起来。

Parameters

NameTypeDescription
iterableIterable[str]要连接的可迭代字符串。

Returns

str

Example

python
','.join(['a', 'b', 'c'])   # 'a,b,c'
'-'.join('abc')            # 'a-b-c'
' '.join(['hello', 'world'])  # 'hello world'
str.strip([chars])

返回移除首尾字符后的副本。默认移除空白字符。

Parameters

NameTypeDescription
charsstr | None要移除的字符(None = 空白字符)。

Returns

str

Example

python
'  hi  '.strip()      # 'hi'
'xxhelloxx'.strip('x')  # 'hello'
str.startswith(prefix[, start[, end]])

如果字符串以 prefix 开头则返回 True。

Parameters

NameTypeDescription
prefixstr | tuple[str, ...]要检查的前缀或前缀元组。
startint起始索引。
endint结束索引。

Returns

bool

Example

python
'hello'.startswith('he')        # True
'file.py'.startswith(('a', 'f'))  # True
str.endswith(suffix[, start[, end]])

如果字符串以 suffix 结尾则返回 True。

Parameters

NameTypeDescription
suffixstr | tuple[str, ...]要检查的后缀或后缀元组。
startint起始索引。
endint结束索引。

Returns

bool

Example

python
'hello'.endswith('lo')        # True
'file.py'.endswith(('.py', '.js'))  # True
str.upper()

返回将所有有大小写的字符转换为大写后的副本。

Returns

str

Example

python
'hello'.upper()  # 'HELLO'
str.lower()

返回将所有有大小写的字符转换为小写后的副本。

Returns

str

Example

python
'HELLO'.lower()  # 'hello'