Home > Back-end >  Remove quotes from a list of tuples in python
Remove quotes from a list of tuples in python

Time:09-03

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)] 

CodePudding user response:

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)]

CodePudding user response:

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)]
  • Related