2016-03-02 136 views
1

有人可以请帮我这一个在Python,我有一个字符串,它看起来像这样:Python的解析字符串

Comm IF Ver 1.18c Port TCP-1 
>R5281H0000 
>L0121 @g 
>E0042A1204C0000 
>[email protected]@L0121 @g 
>S0339E1512 
> 

我想获得从输出的字符串应该是这样的:

R5281H0000 L0121 @g E0042A1204C0000 [email protected]@L0121 @g S0339E1512 
+0

这是从一个文件?或者有很多行的字符串? – Ian

+0

它与6号线的字符串,所以string.count(“\ n”)给出的6 – Dominik

+0

的结果,因为我看到7号线这是不可思议? – Dominik

回答

0

假设这是一个string

a = " \ 
    Comm IF Ver 1.18c Port TCP- \ 
    >R5281H0000 \ 
    >L0121 @g \ 
    >E0042A1204C0000 \ 
    >[email protected]@L0121 @g \ 
    >S0339E1512 \ 
    >" 

考虑使用split得到你的结果

b = a.split('>')[1:-1] #1 is to exclude the first one, -1 to exclude the last one 

产生与你想要的元素列表。

如果你想将它们组合成一些空格的string,使用join

c = " ".join(b) 

编辑一步一步的解释:

什么split确实是“分裂”的字符串根据其分隔符转换为substrings。在这种情况下,分隔符是>,从而改变了长长的一串:

a = " \ 
    Comm IF Ver 1.18c Port TCP- \ 
    >R5281H0000 \ 
    >L0121 @g \ 
    >E0042A1204C0000 \ 
    >[email protected]@L0121 @g \ 
    >S0339E1512 \ 
    >" 

到具有以下元素的字符串列表:

'Comm IF Ver 1.18c Port TCP-' #element no 0 
'R5281H0000' #no 1 
'L0121 @g' #no 2 
'E0042A1204C0000' #no 3 
'[email protected]@L0121 @g' #no 4 
'S0339E1512' #no 5 
'' #no 6 

然后,当你使用切片索引[1:-1],你砍关闭第一和最后一个元素:

'below is b 

'R5281H0000' #no 0, previously 1 
'L0121 @g' #no 1, previously 2 
'E0042A1204C0000' #no 2, previously 3 
'[email protected]@L0121 @g' #no 3, previously 4 
'S0339E1512' #no 4, previously 5 

于是最后,join将列表中的这些字符串回一个字符串通过空间" "

R5281H0000  L0121 @g  E0042A1204C0000  [email protected]@L0121 @g  S0339E1512  
+0

能否请您给我解释一下究竟B = a.split(“>”)[1:-1]的作品,它是做我想要什么,但只是想看看它是如何做的呢? – Dominik

+0

@Dominik解释。希望它能让你更好地理解。 :) – Ian

+0

我仍然在每行的结尾有新行? \ r \ n – Dominik

0

分开我收集的是,你要加入的每个与>有三个空格开头行,但不包括>。以下是如何做到这一点:

print(" ".join(s.lstrip(">") for s in string if s.startswith(">")))