Enumerate#
Another way to iterate (loop) over a list is enumerate()
. With enumerate we’ll get an index
for each item:
words = ['hello', 'world', '!']
# for-loop
for word in words:
print(word)
# for-loop with enumerate
for index, word in enumerate(words):
print(f"{index} : {word}")
hello
world
!
0 : hello
1 : world
2 : !
from fpdf import FPDF
pdf = FPDF(format=(115, 180))
pdf.set_font('Helvetica')
# Store a longer text in the variable 'text'.
text = "Hello, world, with your shades of green and blue, You're here to stay, the morning dew. The vast expanse, the creatures, trees, Each tiny grain of sand at the sea's breeze. A symphony of life, a dance so free, Hello, world, in you we breathe."
# Print the data type
print(type(text))
# Split the text into a list of sentences.
sentences = text.split('.')
# Print the data type
print(type(sentences))
# Print the sentences
print(sentences)
for index, sentence in enumerate(sentences):
pdf.add_page()
pdf.set_font_size(36)
pdf.multi_cell(w=0, text=sentence, align='L')
pdf.set_y(-24)
pdf.set_font_size(10)
pdf.cell(w=0, text=str(index+1), align='R')
pdf.output("pdfs/haiku_enumerate.pdf")
<class 'str'>
<class 'list'>
["Hello, world, with your shades of green and blue, You're here to stay, the morning dew", " The vast expanse, the creatures, trees, Each tiny grain of sand at the sea's breeze", ' A symphony of life, a dance so free, Hello, world, in you we breathe', '']
Split into chunks#
def split_into_chunks(string, chunk_size):
chunks = []
for i in range(0, len(string), chunk_size):
chunks.append(string[i:i+chunk_size])
return chunks
# Example usage
input_string = "This is an example string to be split into chunks of size 10"
chunk_size = 10
chunks = split_into_chunks(input_string, chunk_size)
for chunk in chunks:
print(chunk)
Access list elements with their index#
l = [5, "hello", -1.5, "🐍", "🍕"*9]
print(l[1])
print(l[4])
hello
🍕🍕🍕🍕🍕🍕🍕🍕🍕
print(l[0])
print(l[-1])
5
🍕🍕🍕🍕🍕🍕🍕🍕🍕
from fpdf import FPDF
pdf = FPDF(format=(115, 180))
pdf.set_font('Helvetica')
with open('data/wordlist.txt', 'r') as f:
wordlist = f.readlines()
with open('data/for_loop_haiku.txt', 'r') as f:
haiku = f.read()
# Split the haiku into a list
haiku_lines = haiku.split('\n')
# Iterate over the lines
for index, line in enumerate(haiku_lines):
# Look up the page number through the index
page_number = wordlist[index]
pdf.add_page()
pdf.set_font_size(36)
pdf.multi_cell(w=0, text=line, align='L')
pdf.set_y(-24)
pdf.set_font_size(10)
pdf.cell(w=0, text=page_number, align='R')
pdf.output("pdfs/haiku_enumerate_wordlist.pdf")