sorted
returns a list, and when you print a list, the elements are shown in square brackets, so it’s not that "sorted
returns the brackets", is that the brackets are part of the textual representation of a list, that is, the way it was chosen to display a list in text form (but the brackets themselves are not part of the list, as it only has the values).
If you do not want the brackets shown, then do not print the list directly. An alternative is to turn the list into a single string, using join
, and then you put the parentheses around her:
print(f"A função tem duas raízes reais, que são: ({', '.join(map(str, sorted(raizes, key=int)))}).")
Note the parentheses before and after {
and }
: they will be around the string generated by join
. In the case, join
will put the values separated by ,
(comma and space - and you can trade in whatever you want).
Or, to make it a little clearer what’s going on:
raizes_texto = ', '.join(map(str, sorted(raizes, key=int)))
print(f"A função tem duas raízes reais, que são: ({raizes_texto}).")
In this case, I also used map
along with str
to transform the values into strings, since the join
error if elements are not strings.
I guess it doesn’t make much sense to use key=int
, for then you will be ordering the roots by their entire values. So if you have:
raizes = [2.5, 2.4]
By turning them into int
, both shall be equal to 2
, then they will not change order, because the documentation says that the ordering is stable, that is, it does not change the order of 2 elements if they are considered equal. Therefore, as you have done, the roots will not be ordered if they have values with decimals. If you want to order them, just use sorted
and ready:
raizes_texto = ', '.join(map(str, sorted(raizes)))
print(f"A função tem duas raízes reais, que são: ({raizes_texto}).")
Another alternative is to turn the list into a tuple, because tuples, when printed, show the elements in parentheses:
print(f"A função tem duas raízes reais, que são: {tuple(sorted(raizes))}.")
Although this I find kind of "gambiarra" (as well as solutions that make replace
of the brackets, or anything else that depends on the specific implementation of how the list is printed). A replace
may seem "innocent" and even work for this specific case, but you just have a list in which one of the elements is a string whose text contains a square bracket, to stop everything from working (or a list of lists as the internal lists are also printed with brackets and these will be removed improperly, see an example).
Anyway, if you want a specific format, then build the string explicitly, according to what you want.