簡體   English   中英

python,第二個字符后將字符串拆分為數組

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

我正在捕獲具有以下內容的文件:

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

示例: 原始文件

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

我正在嘗試將每一行放入列表中,並始終獲得一個包含2列的數組。 我試過了

line.split(' ') 

但它不起作用,因為每行的第一或第二個位置可能會出現一個空字符。

因此,我需要在第二個字符之后進行此拆分,這意味着上述文件的結果將是:

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

如果將firl數組索引上的空字符修剪掉,那也是可以接受的

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

使用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']

因此,只需在您自己的代碼中使用以下代碼:

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

或就像@jonClements建議使用line.rpartition(' ')[::2]來確保每個列表都包含兩個元素:

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

如果文件名(固定寬度)前總是有3個字符,則可以使用以下簡單方法:

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

沒有必要做花哨的事情而不是做正確的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM