Home > Software design >  how do I append something to a list after an element not at the end of the list
how do I append something to a list after an element not at the end of the list

Time:12-31

I have a list...

   delimiterList = ["[", "]", "{", "}", ","]

def getData():
    Input = input("Enter JSON")
    return Input

def saveInputAsList(input):
    inputList = []
    for i in input:
        inputList.append(i)
    return inputList

def Format():
    input = saveInputAsList(getData())
    if delimiterList in input:
        input.append('\n')
        return input
        
 

print(Format())
  1. ask user for input, save to list I want to loop through the list
  2. If any strings in my delimiterlist in user input append '\n' to list
  3. the output should be ['a', '"', '\n', 'b', '[', '\n']

I'm trying to work on a JSON beautifier without using libraries

CodePudding user response:

You can use insert method on a list. See python documentation here

This method will help you to insert an element at a given index. If you are looking to the first occurence of an element in a list, you can use index method.

So:


my_list = ['a', 'b', 'c']
my_list.insert(my_list.index('b')   1, 'z')
print(my_list)

will output

['a', 'b', 'z', 'c']
  • Related