Python split()
更新:2022-07-24 13:06
Python 中的 split()
函数通过使用指定的分隔符拆分原始字符串来帮助返回字符串列表。
str.split([separator [, maxsplit]]) # where separator may be a character, symbol, or space
分割()参数:
split()
函数接受两个参数。如果没有给定分隔符参数,它将接受任何空白(空格、换行符等)作为分隔符。
参数 | 描述 | 必需/可选 |
---|---|---|
分离器 | 它是一个分隔符。字符串在指定的分隔符处拆分。 | 可选 |
maxsplit | maxsplit 定义了拆分的最大数量。 | 可选 |
max split 的默认值为-1。 | 可选 |
拆分()返回值
返回值是字符串列表。如果拆分计数是 maxsplit,那么我们在输出列表中有 maxsplit+1 个项目。如果找不到指定的分隔符,则将整个字符串作为元素的列表作为输出返回。
投入 | 返回值 |
---|---|
线 | 字符串列表 |
Python 中 split()
方法的示例
示例 split()
方法在 Python 中是如何工作的?
string = 'Hii How are you'
# splits at space
print(string.split())
fruits = 'apple, orange, grapes'
# splits at ','
print(fruits.split(', '))
# Splits at ':' but not exist so return original
print(fruits.split(':'))
输出:
['Hii', 'How', 'are', 'you']
['apple', 'orange', 'grapes']
['apple, orange, grapes']
示例 2: 指定 maxsplit 时 split()
的工作方式?
fruits = 'apple, orange, grapes, strawberry'
# maxsplit: 2
print(fruits.split(', ', 2))
# maxsplit: 1
print(fruits.split(', ', 1))
# maxsplit: 5
print(fruits.split(', ', 5))
# maxsplit: 0
print(fruits.split(', ', 0))
输出:
['apple', 'orange', 'grapes, strawberry']
['apple', 'orange, grapes, strawberry']
['apple', 'orange', 'grapes', 'strawberry']
['apple, orange, grapes, strawberry']