Python string split on the issue

first question:

Python string comes split method can use only one character string is divided, but the python regular module may implement multiple character segmentation

import re
list1 = re.split('_|#|\|','this_is#a|test')
print(list1)

The result is:

['this', 'is', 'a', 'test']

second question:

More blank string is divided in different lengths, I need to put spaces removed, leaving a list of useful information form, there are two solutions to this problem:

1.split () function can be segmented by default space

str1 = " I miss my      old account "
str1.split()

result:

['I', 'miss', 'my', 'old', 'account']

If written in split ( ""), will be a lot of empty characters appear as follows:

str1 = " I miss my     old account "
str1.split(" ")

result:

['', 'I', 'miss', 'my', '', '', '', '', 'old', 'account', '']

2. can split ( "") filtered with the filter function

str1 = " I miss my     old account "
list1 = filter(None, str1.split(" "))
print(list(list1))

result:

['I', 'miss', 'my', 'old', 'account']

 

Guess you like

Origin blog.csdn.net/a857553315/article/details/85061724