Python has this idea of having a way that is the obvious of solving things - but not always the obvious is so obvious at first sight.
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 do not know the length of before (eg if you are reading from a file) in other languages you may have to use an auxiliary variable to know if it is the first interaction, otherwise 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 the "," for the last element.
In Python, strings have method join
which is very interesting: it concatenates strings of a string using the initial string as a separator. So it never prints the separator at the beginning or end of a sequence.
So if I have:
a = ["Universidade", "de", "Campinas"]
b = " ".join(a)
print(b)
Go display
University of Campinas
The only problem is that being a string method, "join" expects all elements of the string to concatenate to be strings themselves.
Here's another Python element - the language has a syntactic way to synthetically solve everything that resolves repetition (and filters) of a sequence - so-called "mapping and filtering" problems: you use a
for
as part of an expression: you first put the expression you want to use to transform all the elements of the sequence, and then write the "for" - for example:
(elemento * 2 for elemento in sequencia)
It would result in an iterator delivering each element of the initial "sequence" multiplied by 2.
Then, since we want all elements of the vector of numbers 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 enclosed in brackets ( [x for x in y]
) - this always generates a list, with all elements in memory - without the additional brackets, you have a generator
that can be used only once, with the difference that the elements are computed as they are used and are never stored in memory for an instant call to join
that makes no difference.)