How to remove character from tuples in list?

How to remove "(" ,")" form

[('(10', '40)'), ('(40', '30)'), ('(20', '20)')]

by python?

Answers


Depending on how you are currently storing the list:

def to_int(s):
    s = ''.join(ch for ch in s if ch.isdigit())
    return int(s)

lst = [('(10', '40)'), ('(40', '30)'), ('(20', '20)')]

lst = [(to_int(a), to_int(b)) for a,b in lst] # => [(10, 40), (40, 30), (20, 20)]

or

import ast

s = "[('(10', '40)'), ('(40', '30)'), ('(20', '20)')]"
s = s.replace("'(", "'").replace(")'", "'")
lst = ast.literal_eval(s)               # => [('10', '40'), ('40', '30'), ('20', '20')]
lst = [(int(a), int(b)) for a,b in lst] # => [(10, 40), (40, 30), (20, 20)]

Straightforward, use list comprehension and literal_eval.

>>> from ast import literal_eval
>>> tuple_list = [('(10', '40)'), ('(40', '30)'), ('(20', '20)')]
>>> [literal_eval(','.join(i)) for i in tuple_list]
[(10, 40), (40, 30), (20, 20)]

>>> L = [('(10', '40)'), ('(40', '30)'), ('(20', '20)')]
>>> [tuple((subl[0].lstrip("("), subl[1].rstrip(")"))) for subl in L]
[('10', '40'), ('40', '30'), ('20', '20')]

Or if you wan the numbers in your tuples to eventually be ints:

>>> [tuple((int(subl[0].lstrip("(")), int(subl[1].rstrip(")")))) for subl in L]
[(10, 40), (40, 30), (20, 20)]

You can call .strip('()') on individual items (if they are strings, like in your example) to strip trailing ( and ).

There are multiple ways to apply that on single elements:

list comprehension (most pythonic)

a = [tuple(x.strip('()') for x in y) for y in a]

map and lambda (interesting to see)

Python 3:

def cleanup(a: "list<tuple<str>>") -> "list<tuple<int>>":
    return list(map(lambda y: tuple(map(lambda x: x.strip('()'), y)), a))

a = cleanup(a)

Python 2:

def cleanup(a):
    return map(lambda y: tuple(map(lambda x: x.strip('()'), y)), a)

a = cleanup(a)

Process the original string instead. Let's call it a.

On a='((10 40), (40 30), (20 20), (30 10))' , you can call

[tuple(x[1:-1].split(' ')) for x in a[1:-1].split(', ')]

The [1:-1] trims brackets from the string, the splits split strings into lists of strings. The for is a comprehension.


s = "((10 40), (40 30), (20 20), (30 10))"
print [[int(x) for x in inner.strip(' ()').split()] for inner in s.split(',')]

# or if you actually need tuples:
tuple([tuple([int(x) for x in inner.strip(' ()').split()]) for inner in s.split(',')])

Need Your Help

MEAN Stack CRUD update 404 error

node.js angularjs express crud

Heads up, noob coming through. Trying to build a MEAN stack todo list. So far I've gotten everything to work except for the update option. What I've done is set up the application so that it prompt...

Checking if a url is already submitted in database in php

php mysql regex

What i need get done is checking if a url is already submitted in database using php.