3 ways to implement string splitting in Python

 Method 1: Use the split() method

The string type in Python provides the split() method, which is used to split a string into multiple substrings according to the specified delimiter. For example, we can split a comma-separated string into a list:

s = "apple,banana,pear"
print('待分割的字符串为:', s)
lst = s.split(",")
print('分割后为:', lst)  # ['apple', 'banana', 'pear']

Here, the split() method accepts one parameter, the separator, which can be a string or a regular expression. If no delimiter is specified, the split() method defaults to using spaces as the delimiter.

Method 2: Use the splitlines() method

If we need to split a string containing multiple lines of text into multiple lines, we can use the splitlines() method of the string type. For example:

s = "book\npaper\nback"
print('待分割的字符串为:', s)
lst = s.splitlines()
print('分割后为:', lst)

Here, the splitlines() method will split the string into multiple lines based on newline characters and store each line as a string in a list.

Method 3: Use regular expressions

Regular expressions are a powerful tool for matching and processing strings, and they can perform more complex string splitting operations. For example, we can use regular expressions to split a comma- and space-separated string into a list:

import re

s = "face, vehicle, head hat"
print('待分割的字符串为:', s)
lst = re.split(r",\s*", s)
print('分割后为:', lst)

Here, the regular expression ",\s*" matches commas and zero or more spaces, thereby splitting the string.

Guess you like

Origin blog.csdn.net/hanzhuhuaa/article/details/132688836
Recommended