Home > Article > Web Front-end > How to use split() method
The split() method is a method called on the string object. It is used to split the string into substrings and return a list composed of these substrings. The method is "string.split( separator, maxsplit) ", where string is the string to be split, separator is the separator, used to specify at which characters to split, maxsplit is an optional parameter, used to specify the maximum number of splits.
The split() method is a method called on a string object to split the string into substrings and return a list consisting of these substrings. You can use it in the following way split() method:
string.split(separator, maxsplit)
Among them, string is the string to be split, separator is the separator, used to specify which characters to split. maxsplit is an optional parameter, used to specify the maximum number of splits.
Here are some examples:
# 使用空格作为分隔符 text = "Hello World" words = text.split() # 默认使用空格分割 print(words) # 输出: ['Hello', 'World'] # 使用逗号作为分隔符 numbers = "1,2,3,4,5" num_list = numbers.split(',') # 使用逗号分割 print(num_list) # 输出: ['1', '2', '3', '4', '5'] # 指定最大分割次数 text = "one,two,three,four,five" parts = text.split(',', 2) # 最多分割2次 print(parts) # 输出: ['one', 'two', 'three,four,five']
In the above example, we use the split() method to split the string into substrings and store them in a list. You can choose the appropriate one according to your needs delimiter and maximum number of divisions.
The above is the detailed content of How to use split() method. For more information, please follow other related articles on the PHP Chinese website!