Remove the trailing comma when format string with tuples

Viewed 1407

I'm doing string formatting with tuples:

a = (1,2,3)
s = f"something in {a}"
print(s)
'something in (1, 2, 3)'

Everything is fine until I encounter a single-element tuple, which gives:

a = (1,)
s = f"something in {a}"
'something in (1,)'

what I actually want is:

'something in (1)'

How do I make tuple string formatting behaves consistently and remove the trailing comma?

4 Answers

You could use your own formatting logic, e.g.

a = (1,2,3)
s = ','.join([str(x) for x in a])
print(s)  # 1,2,3

a = (1,)
s = ','.join([str(x) for x in a])
print(s)  # 1

Python have 2 magic methods for formatting values: __str__ and __repr__.

__str__ may return any string, but __repr__ must return string that can be passed to eval and recreate value. It's not required, but you should do it. print tries to use __str__ if it's overriden, otherwise it uses __repr__. This means that you can use eval(repr(some_value)) to clone value, because most builtin types have overridden __repr__ properly. That's why you get trailing comma when formatting (1,).

If you really want to format tuple without trailing comma then use

def format_tuple(value):
    return "(" + ",".join(repr(v) for v in value) + ")"
# (1,) -> "(1)"
# () -> "()"
# (1, 2, 3,) -> "(1, 2, 3)"
# (1, 2, 3) -> "(1, 2, 3)"

You can use regex:

import re

tuple = (1,)
s = "something in "  + re.sub(r',(?=\))', '', str(tuple))
print(s)

Result:

something in (1)

You don't need any for loop etc.

Based on @Tim Biegeleisen's answer:

a = (1,)
s = f"something in ({','.join([str(x) for x in a])})"
print(s)
'something in (1)'
Related