split() function in python

1. Description

split() slices the string by the specified delimiter, if the parameter num has a specified value, it is separated into num+1 substrings

2. Grammar

split() method syntax:

str.split(str="", num=string.count(str)).

parameter:

  • str – delimiter, the default is all null characters, including spaces, newlines (\n), tabs (\t), etc.
  • num – the number of splits. Defaults to -1, which separates all.
    Return Value
    Returns the split string list.

3. Example

str = "sdfsg gowjegig wepgnp wegjp";
    print(str.split())  # 以空格为分隔符,包含 \n
    print(str.split(' ', 1))  # 以空格为分隔符,分隔成两个
    print(str.split(' ', 2))  # 以空格为分隔符,分隔成三个

# ['sdfsg', 'gowjegig', 'wepgnp', 'wegjp']
# ['sdfsg', 'gowjegig wepgnp wegjp']
# ['sdfsg', 'gowjegig', 'wepgnp wegjp']

Four. Summary

The split function is used to process the incoming string. For example, the last character of each line in the content obtained from the file is \n, which is a newline character, which can be deleted through the split function.

Guess you like

Origin blog.csdn.net/weixin_46769840/article/details/127336963