I am trying to count the words in a list to insert a line break in the middle of them.
def salto_linea_nombre(nombre_empresa):
"""
Separa el nombre y cuenta el numero de palabras para inserta un salto de linea en medio de ellas
:param nombre_empresa:
:return: salto_nombre
"""
from math import floor
separacion = nombre_empresa.split()
pibote = int(floor(len(separacion)/2))
salto_nombre = ""
for palabra in separacion:
salto_nombre = salto_nombre + " " + palabra
if pibote ==
salto_nombre = salto_nombre + "\n"
return salto_nombre
I need to know what iteration I am in to add the line break in the right place, I know that I can add a variable that is initialized to 0 and that is increased in each iteration. But I also know that there is a "more python" way using two variables in the for, but I don't remember how to use it
What you're describing is the built-in
enumerate
, which takes an iterable as an argument and generates tuples of the form(contador, elemento)
starting count from zero on each call to its method__next__
:Note that the above function creates a space before the first word and another after the line break, which you may not want.
You can use a combination of
str.join
and list slicing to get what you want more directly and without the aforementioned spaces:Notice that I've removed
math.floor
, since you always apply it to a positive number, you can simply truncate, in this case by applying integer division (//
).