Python has this idea of having a way that is the obvious way to solve things - but not always the obvious is so obvious at first glance.
This problem always gets ugly in other languages, just because you have to leave a special case for the last element.
So, in the case of a sequence that you don’t know the length beforehand, (for example, if you’re reading from a file) in other languages you may have to use an auxiliary variable to know if it’s the first interaction, but print the "," at the beginning of the loop:
primeiro = True
for i in sequencia:
if not primeiro:
print(", ", end="")
primeiro = False
print(i)
print()
If the sequence has known length, such as a list, you can do an "if" and not print ", " to the last element.
In Python, strings have the method join
which is very interesting: it concatenates strings from a sequence using the initial string as a separator. So he never prints the separator either at the beginning or at the end of a sequence.
So if I have:
a = ["Universidade", "de", "Campinas"]
b = " ".join(a)
print(b)
Will display
University of Campinas
The only problem is that being a string method, "Join" expects all elements of the sequence that will concatenate to be themselves strings.
Then comes another element of Python - the language has a syntactic way to solve in a synthetic way everything that solves repetition (and filters) of a sequence - the so-called "mapping and filtering" problems: you use a for
as part of an expression: you put first the expression you want to use to transform all elements of the sequence, and then type "for" - for example:
(elemento * 2 for elemento in sequencia)
It would result in an iterator that delivers each element of the initial "sequence" multiplied by 2.
So, since we want all the elements of the number array transformed into a string before calling "Join", just do:
print(", ".join(str(i) for i in range(12)))
To make your impression of the elements interspersed with ", ".
(Note that there is a difference if the "for" of an expression is placed between brackets ([x for x in y]
)- this always generates a list, with all the elements in memory - without the additional brackets, you have a generator
which can be used only once, except that the elements are computed as they are used and are never stored all in memory. For an immediate flame to join
it makes no difference).
For aesthetic questions (exhibition only), it would be possible to do only
print(str(numeros)[1:-1])
. If the return is used for anything else, usejoin
.– Woss
Thanks! I decided to use your first suggestion to solve my problem.
– user70765
guy - the approache "less pythonic" is not "much simpler". Join with genertor Expression is the right way to do this (but not with map, map really breaks readability).
– jsbueno