在Python中,`split()` 是一个字符串方法,用于将字符串分割成子字符串,并将这些子字符串存储在列表中,`split()` 方法可以通过指定分隔符对字符串进行切片。
以下是 `split()` 方法的语法:
str.split(str, max)
`str` 是分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等,`max` 是分割次数,如果不指定,则根据字符串中有多少个分隔符,就分隔多少次。
以下是一些使用 `split()` 方法的示例:
1. 使用空格作为分隔符:
string = "hello world" result = string.split() print(result) # 输出:['hello', 'world']
2. 使用指定的分隔符:
string = "apple,orange,banana" result = string.split(",") print(result) # 输出:['apple', 'orange', 'banana']
3. 指定分割次数:
string = "apple,orange,banana,grape" result = string.split(",", 2) print(result) # 输出:['apple', 'orange', 'banana,grape']
4. 使用默认的分隔符(空格、换行、制表符):
string = "hello\nworld" result = string.split() print(result) # 输出:['hello', 'world']