在Python中处理字符串:以一种非常特定的方式格式化信息



OBS:我正在使用Python 3.5.2,我使用标准Shell和IDLE

大家好,我认为用python编程时最困难的任务之一是处理字符串。有人能帮忙吗?

我经常遇到的一个问题是转换字符串以便我可以正确地使用它。例如:

#consider I have the following string I want to work with:

my_input = 'insert 3 ["psyduck", 30]!!!insert 10 ["a nice day at the beach", 100]!!!find 3!!!find 10'

我如何转换这个字符串,在结果中,我将能够做以下事情:

1 -像这样将以下子字符串分隔成变量:

command = 'insert'
node = '3' #or the int 3
list = '["psyduck", 30]'

2 -或任何其他解决方案,以某种方式使我最终做到这一点:

listOfCommands = [['insert', '3', '["psyduck", 30]'], ['insert', '10', '["a nice day at the beach", 100]'], ['find', '3'], ['find', '10']]

我需要这个列表,以便做以下事情:

for entry in listOfCommands:
    if entry[0] == 'insert':
    #I will execute a part of the program    
    elif entry[0] == 'update':
    #execute something else
    elif entry[0] == 'find':
    #execute something else

问题是我不知道输入中将会出现什么(命令的数量或我必须添加的信息的大小)。我只知道它将始终遵循这些精确的格式:[一个命令,一个'节点',我必须存储或更新它,我必须存储或更新的信息][一个命令,一个'节点',我必须找到或删除]和块将由'!!'

我可以在主程序周围工作,但是为了能够使它正常运行,我需要以这种特定的方式格式化这个输入

也许这样做会起作用:

commands = my_input.split('!!!')
my_commands = [c.split(' ', 2) for c in commands]

split方法的第二个参数告诉它你希望它分割字符串多少次

相关内容

最新更新