str
10 methods内置字符串类型。Unicode 码点的不可变序列。
str.split(sep=None, maxsplit=-1)返回按 sep 分割的子字符串列表。如果 sep 为 None,则按任意空白字符分割并丢弃空字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| sep | str | None | 用于分割的分隔符。None 表示按空白字符分割。 |
| maxsplit | int | 最大分割次数(-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
| Name | Type | Description |
|---|---|---|
| old | str | 要替换的子字符串。 |
| new | str | 替换后的字符串。 |
| count | int | 最大替换次数(-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
| Name | Type | Description |
|---|---|---|
| sub | str | 要查找的子字符串。 |
| start | int | 起始索引(包含)。 |
| end | int | 结束索引(不包含)。 |
Returns
int
Example
python
'hello world'.find('world') # 6
'hello'.find('z') # -1
'abcabc'.find('a', 1) # 3str.format(*args, **kwargs)使用替换字段 {0}、{name} 等格式化字符串。f-strings 的前身。
Parameters
| Name | Type | Description |
|---|---|---|
| *args | Any | 用于编号字段的位置参数。 |
| **kwargs | Any | 用于命名字段的关键字参数。 |
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
| Name | Type | Description |
|---|---|---|
| iterable | Iterable[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
| Name | Type | Description |
|---|---|---|
| chars | str | None | 要移除的字符(None = 空白字符)。 |
Returns
str
Example
python
' hi '.strip() # 'hi'
'xxhelloxx'.strip('x') # 'hello'str.startswith(prefix[, start[, end]])如果字符串以 prefix 开头则返回 True。
Parameters
| Name | Type | Description |
|---|---|---|
| prefix | str | tuple[str, ...] | 要检查 的前缀或前缀元组。 |
| start | int | 起始索引。 |
| end | int | 结束索引。 |
Returns
bool
Example
python
'hello'.startswith('he') # True
'file.py'.startswith(('a', 'f')) # Truestr.endswith(suffix[, start[, end]])如果字符串以 suffix 结尾则返回 True。
Parameters
| Name | Type | Description |
|---|---|---|
| suffix | str | tuple[str, ...] | 要检查的后缀或后缀元组。 |
| start | int | 起始索引。 |
| end | int | 结束索引。 |
Returns
bool
Example
python
'hello'.endswith('lo') # True
'file.py'.endswith(('.py', '.js')) # Truestr.upper()返回将所有有大小写的字符转换为大写后的副本。
Returns
str
Example
python
'hello'.upper() # 'HELLO'str.lower()返回将所有有大小写的字符转换为小写后的副本。
Returns
str
Example
python
'HELLO'.lower() # 'hello'