How to split a string in Python

How to split a string in Python

.split () method

In Python, represented as a string str immutable objects. str class with many string methods that allow you to manipulate strings.

.split () method returns a list of strings separated by sub delimiters. It uses the following syntax:

str.split (share = None, maxsplit = -1)

Separator may be a character or sequence of characters, rather than the regular expression.

In the following example, the string s separated by commas as separators.

The result will be a list of strings:

Output is as follows:

How to split a string in Python

Text strings are usually enclosed in single quotes, double quotes may be used.

Sequence of characters can also be used as a separator:

Output is as follows:

How to split a string in Python

When given maxsplit, it will limit the number of divisions. Or -1 if not specified, there is no limit on the number of divisions. (Maxsplit is is the number of isolated, maxsplit = 1 once separated, the default is 0, the number is not limited.)

The results list with the greatest maxsplit + 1 elements:

Output is as follows:

How to split a string in Python

If not specified delim or a Null, the space will be used as a separator to split the string. All consecutive spaces are treated as a single delimiter. Further, if the string contains trailing and leading spaces, the result will not be the empty string.

To better illustrate this point, let's look at the following example:

'LinuxIDC.com LinuxMi.COM Linuxidc LinuxIDC' .split ()

Output is as follows:

[ 'LinuxIDC.com', 'LinuxMi.COM', 'Linuxidc', 'LinuxIDC']

How to split a string in Python

Look

'LinuxIDC.com LinuxMi.COM Linuxidc LinuxIDC' .split ( '')

Output is as follows:

[ '' 'LinuxIDC.com', '', 'LinuxMi.COM', '', 'Linuxidc', 'LinuxIDC' '']

How to split a string in Python

If no delimiters are used, the returned list does not contain an empty string. If the delimiter is set to spaces '', the leading, trailing, and the results will lead to continuous spaces contains an empty string.

to sum up

Split string is one of the most basic operations. After reading this tutorial, you should have a good understanding of how to split a string in Python.

If you have any questions or feedback, please feel free to comment.

Guess you like

Origin www.linuxidc.com/Linux/2019-07/159511.htm