Ericthm Ericthm - 8 months ago 35
Python Question

Working with strings in Python: Formatting the information in a very specific way

OBS: I am working on Python 3.5.2 and I use the standard Shell and IDLE

Hi everyone, I think one of the most difficult tasks I have when programming with python is dealing with strings. Is there someone who can help?

One of the problems I face frequently is transforming the string so I can use it properly. For instance:

#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'

How can I transform this string in a way that, with the results, I would be able to do the following:

1 - Separate the following substrings into variables like this:

command = 'insert'

node = '3' #or the int 3

list = '["psyduck", 30]'

2 - Or any other solution that will somehow enable me to do this in the end:

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

I need this list in order to do the following:

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

The problem is that I do not know exaclty what is going to appear (the number of commands or the size of the information I will have to add) in the input. I just know that it will always obey these exact formats:
[A command, a 'node' where I have to store the information or update it, the information I have to store or update] or [A command, a 'node' I have to find or delete] and the blocks will be separated by '!!!'

I can work my way around the main program but in order to be able to make it run properly, I need to have this input formatted in this really specific way.


Maybe something like this will work:

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

The second argument of the split methods tells it how many times you want it to split the string.