Python 字符串 split() 方法
定义和用法
split() 方法将字符串拆分为列表。
您可以指定分隔符,默认分隔符是任何空白字符。
注释:若指定 max,列表将包含指定数量加一的元素。
实例
例子 1
将字符串拆分成一个列表,其中每个单词都是一个列表项:
txt = "welcome to China" x = txt.split() print(x)
例子 2
使用逗号后跟空格作为分隔符,分割字符串:
txt = "hello, my name is Bill, I am 63 years old"
x = txt.split(", ")
print(x)
例子 3
使用井号字符作为分隔符:
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
例子 4
将字符串拆分为最多 2 个项目的列表:
txt = "apple#banana#cherry#orange"
# 将 max 参数设置为 1,将返回包含 2 个元素的列表!
x = txt.split("#", 1)
print(x)
语法
string.split(separator, max)
参数
| 参数 | 描述 |
|---|---|
| separator |
可选。规定分割字符串时要使用的分隔符。 默认值为空白字符。 |
| max |
可选。规定要执行的拆分数。 默认值为 -1,即“所有出现次数”。 |