简体   繁体   English

python,第二个字符后将字符串拆分为数组

[英]python, split string into array after second character

I'm capturing a file with the following content: 我正在捕获具有以下内容的文件:

*> <'Char><'Char><'space><'string>*

example: Original File 示例: 原始文件

Fs .file1
 M /home/file2
?? /home/file3
M  /home/file4
 D /home/file5

I'm trying to get each line into a list and get always one array with 2 columns. 我正在尝试将每一行放入列表中,并始终获得一个包含2列的数组。 I tried 我试过了

line.split(' ') 

but it is not working since an empty char might happen on the first or second position of each row. 但它不起作用,因为每行的第一或第二个位置可能会出现一个空字符。

so, I need to do this split after the second character, meaning the result of the above file will be: 因此,我需要在第二个字符之后进行此拆分,这意味着上述文件的结果将是:

['Fs','.file1']
[' M','./home/file2']
['??','./home/file3']
['M ','./home/file4']
[' D','./home/file5']

It would be also acceptable if the empty character on the firl array index is trimmed 如果将firl数组索引上的空字符修剪掉,那也是可以接受的

['Fs','.file1']
['M','./home/file2']
['??','./home/file3']
['M ','./home/file4']
['D','./home/file5']

Use rsplit presuming the contents all look like you have in your question: 使用rsplit假定内容看起来像您在问题中一样:

lines ="""Fs .file1
 M /home/file2
?? /home/file3
M  /home/file4
 D /home/file5"""

for line in lines.splitlines():
    # splitting once on " " starting from the right 
    # side keep all whitespace on the left elements
    print(line.rsplit(" ",1))

['Fs', '.file1']
[' M', '/home/file2']
['??', '/home/file3']
['M ', '/home/file4']
[' D', '/home/file5']

So simply use the following in your own code: 因此,只需在您自己的代码中使用以下代码:

print [line.rstrip().rsplit(" ",1)for line in f]

Or as @jonClements suggests use line.rpartition(' ')[::2] to always make sure we get two elements per list: 或就像@jonClements建议使用line.rpartition(' ')[::2]来确保每个列表都包含两个元素:

print [line.rpartition(' ')[::2] for line in f]

If there are always 3 characters before the filename (fixed width) then do the simple way: 如果文件名(固定宽度)前总是有3个字符,则可以使用以下简单方法:

flags, filename = line[:2], line[3:]

There is no need to do fancy instead of the right thing. 没有必要做花哨的事情而不是做正确的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM