假设这是一个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
来源
2016-03-02 02:57:26
Ian
这是从一个文件?或者有很多行的字符串? – Ian
它与6号线的字符串,所以string.count(“\ n”)给出的6 – Dominik
的结果,因为我看到7号线这是不可思议? – Dominik