Remove quotes from a list of tuples in python

Question:

Hoping someone can help me to figure out how to exclude quotes from a list of tuples and display it in the final output. I’ve tried regex a nd f-string format but nothing seem to work 🙁

lts = [('A', 1), ('B', 14), ('C', 12), ('D', 11), ('E', 9)]
Regex - [(re.sub(r"[^a-zA-Z0-9 ]", "", l[0]), l[1]) for actor in lst]
F-string - f'{l[0]}, {l[1]}' for l in lst]

desired_output = [(A, 1), (B, 14), (C, 12), (D, 11), (E, 9)] 
Asked By: Janey Jane

||

Answers:

Code:

lts = [('A', 1), ('B', 14), ('C', 12), ('D', 11), ('E', 9)]
a = "["
b = []
for l in lts:
    b.append( f"({l[0]},{l[1]})" )
e = ", ".join(b)
print(e)
for each in e:
    a += each
a += f"]"
print(a)

Output

(A,1), (B,14), (C,12), (D,11), (E,9)
[(A,1), (B,14), (C,12), (D,11), (E,9)]
Answered By: Wayne

In case A, B, … are defined variables, you could do the following:

A, B, C, D, E = 1, 2, 3, 4, 5
desired_output = [(globals()[k], v) for k, v in lts]
print(desired_output)

which prints

[(1, 1), (2, 14), (3, 12), (4, 11), (5, 9)]

In case you simply want a string representation of lts without the quotes, you could do the following:

desired_output = repr(lts).replace("'", '')
print(desired_output)

which prints

[(A, 1), (B, 14), (C, 12), (D, 11), (E, 9)]
Answered By: Michael Hodel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.