Is it possible to place two separators in string split() method?

瘦欲@ 提交于 2020-06-17 13:13:08

问题


Sorry for the lack of better title.

Hopefully the explanation below help. Given the following string:

 f=' Sleep stage W\\x14\\x00+26070\\x1590\\x14 Sleep stage W\\x14\\x00+26070\\x1590\\x14 Movement time\\x14\\x00+28110\\x15120\\x14 Sleep stage  3\\x14\\x00+28230\\x1530\\x14'

and are to be split as below

' W\\x14\\x00+26070\\x1590\\x14 '
' W\\x14\\x00+26070\\x1590\\x14 '
' \\x14\\x00+28110\\x15120\\x14 '
'  3\\x14\\x00+28230\\x1530\\x14'

To realise this, the following code was drafted

f=' Sleep stage W\\x14\\x00+26070\\x1590\\x14 Sleep stage W\\x14\\x00+26070\\x1590\\x14 Movement time\\x14\\x00+28110\\x15120\\x14 Sleep stage  3\\x14\\x00+28230\\x1530\\x14'
raw_hypno = [x for x in f.split('Sleep stage')][1:]

which produce the following Output

' W\\x14\\x00+26070\\x1590\\x14 '
' W\\x14\\x00+26070\\x1590\\x14 Movement time\\x14\\x00+28110\\x15120\\x14 '
'  3\\x14\\x00+28230\\x1530\\x14'

As can be seen, the detail Movement time was not properly split.

May I know whether it is possible to assign two split condition using the split approach?


回答1:


Using Regex --> re.split.

Ex:

f=' Sleep stage W\\x14\\x00+26070\\x1590\\x14 Sleep stage W\\x14\\x00+26070\\x1590\\x14 Movement time\\x14\\x00+28110\\x15120\\x14 Sleep stage  3\\x14\\x00+28230\\x1530\\x14'
print(re.split(r"Sleep stage|Movement time", f))

Output:

[' ', ' W\\x14\\x00+26070\\x1590\\x14 ', ' W\\x14\\x00+26070\\x1590\\x14 ', '\\x14\\x00+28110\\x15120\\x14 ', '  3\\x14\\x00+28230\\x1530\\x14']



回答2:


You can first replace all the 'Movement time' into 'Sleep stage',

then simply split by 'Sleep stage':

f=' Sleep stage W\\x14\\x00+26070\\x1590\\x14 Sleep stage W\\x14\\x00+26070\\x1590\\x14 Movement time\\x14\\x00+28110\\x15120\\x14 Sleep stage  3\\x14\\x00+28230\\x1530\\x14'.replace('Movement time','Sleep stage').split('Sleep stage')


来源:https://stackoverflow.com/questions/62304371/is-it-possible-to-place-two-separators-in-string-split-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!