帮助Python字符串

mik*_*kip 1 python string

我有一个程序从文本文件中读取命令

例如,命令语法如下,是一个字符串

'index command param1 param2 param3'

参数个数从0到3变量索引是一个整数命令,是一个字符串,所有参数都是整数

我想拆分它们,以便我有一个如下列表

[index,'command',params[]]

做这个的最好方式是什么?

谢谢

Rob*_*tie 8

不确定这是不是最好的方式,但这是一种方式:

lines = open('file.txt')
for line in lines:
   as_list = line.split()
   result = [as_list[0], as_list[1], as_list[2:]]
   print result
Run Code Online (Sandbox Code Playgroud)

结果将包含

['index', 'command', ['param1', 'param2', 'param3']]
Run Code Online (Sandbox Code Playgroud)


Jam*_*kin 5

def add_command(index, command, *params):
    index = int(index)
    #do what you need to with index, command and params here

with open('commands.txt') as f:
    for line in f:
        add_command(*line.split())
Run Code Online (Sandbox Code Playgroud)