caliGeek
caliGeek

Reputation: 419

Remove the comma which appears after converting a json array to tuples

I have an array of values within a json array. I wanted to convert those values to pairs of tuples which i already did but for some reason have a comma appearing at the end of every tuple pair. Can someone please guide me on how to remove the comma.

JSON :

m=    [
            [
                [
                    -118.221524,
                    34.034603
                ],
                [
                    -118.273798,
                    34.038365
                ]
            ]
        ]

Researched online to see how can i apply formatting to remove the comma

for i in m:
    for j in i:
        lines=tuple(j)
        a = []
        a.append(lines)
        print(tuple(a))

Expected:

((-118.27373, 34.038352))
((-118.273798, 34.038365))

Actual:

((-118.27373, 34.038352),)
((-118.273798, 34.038365),)

Upvotes: 2

Views: 651

Answers (2)

Sam Gomena
Sam Gomena

Reputation: 1479

In Python, tuples are printed (and more or less defined) as having a trailing comma (more on this here. You can see the source here that actually writes the repr of a tuple object (assuming you're using a CPython interpreter).

Though, if you're willing to forgo using a a tuple and instead use a list (which it looks like you're already trying to do) you can instead do this:

for i in m:
    for j in i:
        lines=tuple(j)
        a = []
        a.append(lines)
        # Notice this prints `a` which is an array and not a tuple
        print(a)

# prints:
# [(-118.27373, 34.038352)]
# [(-118.273798, 34.038365)]

If you do indeed want to use a tuple, you're best bet is likely then to do some manual formatting on the outer tuple like so:

for i in m:
    for j in i:
        lines=tuple(j)
        a = []
        a.append(lines)
        # Notice this prints `a` which is an array and not a tuple
        a = tuple(a)
        print("({})".format(a[0]))

# ((-118.221524, 34.034603))
# ((-118.273798, 34.038365))

Hope this helps!

Upvotes: 1

Skrino
Skrino

Reputation: 510

The only way to remove the comma is to not print the tuple itself (i.e. print(tuple(a))) as the comma is added by the python implementation to signal that it is a tuple.

Instead, you can create a function that ingests a 1-D tuple (for a simpler example) and creates a custom string that is then printed, a la:

def print_tuple(t):
    s = '(('
    for i, val in enumerate(t):
        s += f'{t[i]}'
        if i != len(t) - 1:
            s += ', '
    s += '))'
    print(s)

# test
a = tuple([1,2,3])
print_tuple_1d(a)  # prints: ((1, 2, 3))

Upvotes: 1

Related Questions