Reputation:
python's join
method ignores the last element in the list, but I want to be able to display without problems, look at my code:
import re
estoque = [0,1,20,0]
estoque_formated = '\n'.join([str(elem) for elem in estoque])
tamanho = [20, 34, 34.5, 40]
joined = f' Em estoque: {estoque_formated[0]}\n'.join(["Tamanho: " + str(elem) for elem in tamanho])
print(joined)
The output of the script I want is this:
Tamanho: 20 Em estoque 0
Tamanho: 34 Em estoque 1
Tamanho: 34.5 Em estoque 20
Tamanho: 40 Em estoque 0
Obs, notice that the sizes are displayed, but it always takes the index 0 of the variable estoque_formated
how can I get the first index and add it? Example starting from 0 and going to 1 then 2...etc? Well, I need to solve the problem with the index as I said, and to get it I was able to display the size and value of the estoque_formated
variable even though it's the last element, I want to modify the script as little as possible.
Upvotes: 1
Views: 134
Reputation: 39354
Ok, so you only need to join
the resulting strings right at the end. You need zip()
to pair up items from two different lists:
estoque = [0,1,20,0]
tamanho = [20, 34, 34.5, 40]
joined = [f'Tamanho: {t} Em estoque: {s}' for t,s in zip(tamanho,estoque)]
print('\n'.join(joined))
Output as requested (moved the '\n'
)
Upvotes: 1
Reputation: 662
You could just write
estoque = [0, 1, 20, 0]
tamanho = [20, 34, 34.5, 40]
print(*(f"Tamanho: {t} Em estoque: {e}" for t, e in zip(tamanho, estoque)), sep="\n")
To get a properly padded output you could format the values accordingly:
print(*(f"Tamanho: {t:4} Em estoque: {e:2}" for t, e in zip(tamanho, estoque)), sep="\n")
which would result in
Tamanho: 20 Em estoque: 0
Tamanho: 34 Em estoque: 1
Tamanho: 34.5 Em estoque: 20
Tamanho: 40 Em estoque: 0
Upvotes: 0
Reputation: 4779
Why use join
when you could just iterate over the two lists and print as you need.
estoque = [0,1,20,0]
tamanho = [20, 34, 34.5, 40]
for i in range(4):
print(f'Tamanho: {tamanho[i]}\tEm estoque: {estoque[i]}')
Output:
Tamanho: 20 Em estoque: 0
Tamanho: 34 Em estoque: 1
Tamanho: 34.5 Em estoque: 20
Tamanho: 40 Em estoque: 0
Upvotes: 0