If you want exactly the texts "First", "Second", etc., there is no direct way - at least natively - to get it. The way is to build the texts yourself, or use an external module.
If you choose to build texts manually, an alternative would be to have a list of options:
distancia = # código para preencher a lista é igual ao seu
ordinais = ['Primeiro', 'Segundo', 'Terceiro', 'Quarto', 'Quinto' ]
for i, salto in enumerate(distancia):
print(f'{ordinais[i]} salto: {salto}')
Another option, as indicated in the comments, is to use zip
to browse both lists simultaneously:
for ordinal, salto in zip(ordinais, distancia):
print(f'{ordinal} salto: {salto}')
The detail is that zip
ends when the shortest of the lists ends, so you have to ensure that there are enough texts on ordinais
so that no element of distancia
stay out (actually, in the first option you also have to ensure this, otherwise a jump will be without the corresponding text).
So another more general option is to use itertools.zip_longest
, which is similar to zip
, but iterates to the end of the largest list, and the missing elements of the smallest list are, by default, equal to None
. In case you have more jumps than text, you could put the suffix º
, as suggested by the other reply (but if you have the text, use it):
distancia = ...
ordinais = ['Primeiro', 'Segundo', 'Terceiro', 'Quarto', 'Quinto' ]
from itertools import zip_longest
for i, (ordinal, salto) in enumerate(zip_longest(ordinais, distancia), start=1):
if salto is None: # não há mais saltos, pare o loop
break
if ordinal is None: # não há mais textos, usa o número e o sufixo º
ordinal = f'{i}º'
print(f'{ordinal} salto: {salto}')
But this option is kind of limited, because if it is possible a very large amount of jumps, the list ordinais
will become huge.
In this case, another option is to use some external module. An alternative is the num2words
:
from num2words import num2words
for i, salto in enumerate(distancia, start=1):
print(f'{num2words(i, to="ordinal", lang="pt_BR").capitalize()} salto: {salto}')
The detail is that this module returns the string with lowercase letters ("first", "second", etc), so I use capitalize
to change the first letter to uppercase.
In the first example, instead of using the
enumerate
just to accessordinais
by index it would not be better to already use azip
direct? Or azip_longest
if the length ofordinais
is a problem?– fernandosavio
@fernandosavio Yes. I updated the reply, thank you! :-)
– hkotsubo
I almost forgot the +1. ;)
– fernandosavio