R2D2
R2D2

Reputation: 71

Python How do I remove leading carriage return from my print results?

I Have the following code that loops through a list. It also uses an eval function to add, remove, and delete from the list. How do I remove leading carriage return from my print results? Not trailing carriage returns.

if __name__ == '__main__':
    N = int(12)
    O = ["insert 0 5",
        "insert 1 10",
        "insert 0 6",
        "print",
        "remove 6",
        "append 9",
        "append 1",
        "sort",
        "print",
        "pop",
        "reverse",
        "print"]
    J = []
    p = []
    for i in range(0, N, 1):
        K = O[i]
        if K.lstrip("\n").find(" ") > 0:
            AK = K[0:K.find(" ")] + \
                "(" + str(K[K.find(" ")+1:]).replace(" ", ",") + ")"
        else:
            AK = K + "()"
        try:
            eval("p."+AK.lstrip("\n"))
        except (NameError, AttributeError):
            eval(AK.lstrip("\n"))
            print(p, sep="", end="")
OutPut below:

enter image description here

Upvotes: 0

Views: 130

Answers (1)

crackaf
crackaf

Reputation: 552

Your line AK=K+'()' is making print() command. And there is nothing like p.print() for lists that's why it raised an exception and eval(AK.lstrip("\n")) moves to the new line.

EDIT: Code on demand:

if __name__ == '__main__':
    N = int(12)
    O = ["insert 0 5",
         "insert 1 10",
         "insert 0 6",
         "print",
         "remove 6",
         "append 9",
         "append 1",
         "sort",
         "print",
         "pop",
         "reverse",
         "print"]
    J = []
    p = []
    for i in range(0, N, 1):
        K = O[i]
        if K.lstrip("\n").find(" ") > 0:
            AK = K[0:K.find(" ")] + \
                "(" + str(K[K.find(" ")+1:]).replace(" ", ",") + ")"
        else:
            if K=="print": AK=K
            else: AK = K + "()"
        try:
            if AK=="print": eval(f"{AK}({p})")
            else: eval("p."+AK.lstrip("\n"))
        except (NameError, AttributeError):
            print("something wrong")

#Output
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

Upvotes: 1

Related Questions