如何解析这个字符串

时间:2013-04-03 11:32:02

标签: python regex python-3.x

如何使用python解析此字符串(可能使用re模块)并使用此数据创建数组?

map: mp_rust
num score ping guid                             name            lastmsg address               qport rate
--- ----- ---- -------------------------------- --------------- ------- --------------------- ----- -----

2 个答案:

答案 0 :(得分:3)

使用固定宽度格式,string slicing可能是解析的最佳方式:

num = s[0:3]
score = s[4:9]
ping = s[10:14]
guid = s[15:47]
name = s[48:63]
 ...

请确保strip远离多余的空格,并在必要时转换为int

您可以通过将结果存储在list

中来创建结果的“数组”
arr = [num, score, ping, guid, name, lastmsg, address, qport, rate]

答案 1 :(得分:0)

除非你知道确切的数据长度(名称可以是“jack”或“theodore”,只是说),所以在空格处分割可能是一种更聪明的方法。它是字符串切片而不是静态。

>>> s = 'num score ping guid                 name            lastmsg address'
>>> num, score, ping, guid, name, lastmsg, address = s.split()

如果这些值可能包含空格,那么你必须使用正则表达式。

相关问题