TL;DR
nums = [2, 5, 7, 9]
valor = "".join(nums)
print(valor) # "2579"
Motive
By checking the job documentation print
you will note the following sentence:
All non-keyword Arguments are converted to strings like str()
does and Written to the stream...
Free translation:
All unnamed arguments are converted to strings like str()
and then written in stream...
That is to say, print(lista)
has the same result as print(str(lista))
* because the list is converted to string. You can check that str([1, 2, 3]) == '[1, 2, 3]'
, that is, a string containing the list elements separated by ", "
and wrapped in clasps.
* In theory they should always be the same results, but I did not perform tests with all native types and custom classes.
Therefore, to customize the way you want to show your list, just access it element by element or using specific methods.
Using str.join()
The method str.join()
binds the elements of a string iterable and concatenates with a separator.
Since your list is integer, you will need to convert the values to string before using the method str.join()
. You can do it using map
(string = map(str, nums)
) or list comprehensions (string = [str(n) for n in nums]
).
Ex.:
nums = [2, 5, 7, 9]
valor = "".join(str(n) for n in nums)
print(valor) # "2579"
demo_2 = "-".join(map(str, nums))
print(demo_2) # "2-5-7-9"
demo_3 = ", ".join(map(str, nums))
print(demo_3) # "2, 5, 7, 9"
Using print()
You can print element by element without spaces between them using the parameter end
of function print()
:
nums = [2, 5, 7, 9]
for n in nums:
print(n, end="") # "2579"
for n in nums:
print(n, end="-") # "2-5-7-9"
for n in nums:
print(n, end=", ") # "2, 5, 7, 9"
I didn’t quite understand... I created an example and it worked like you expect, take a look: https://repl.it/repls/ReflectingHummingTriangle
– Daniel Mendes
Yes, it receives the list in the VAR variable and prints it. I wanted to receive only the items. For then, when printing, instead of printing [2,5,7,9], which is what he gets, print only her items out of a list, like 2579.
– MatRaPy
This answers your question? Remove the brackets from the Sorted function()
– Daniel Mendes
It doesn’t answer exactly, but it helped me understand that there are other possibilities, like turning into a tuple. Thank you very much, man!
– MatRaPy