Python Forum

Full Version: fString Nested forLoop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,
I'm learning about f-strings and I know in theory nested for loops can be turned into a simpler f-string, but I'm not sure how.
rows = range(1, 10)
columns = range(1, 5)
for row in rows:
  for col in columns:
    wb.active.cell(row, col).value = 'fString_forLoop'
Any clues?
thanks,
phil
wb.active.cell(row, col).value = f'row:{row}, column:{col}'
Hi,
Thanks for the code line.
Regarding that f-String:
wb.active.cell(row, col).value = f'row:{row}, column:{col}'
can we break this down a bit?

wb.active # openpyxl method to assign an active worksheet
.cell # openpyxl method to activate a spreadsheet cell
(row, col) # where are you pulling this from?  The only usable code from above is 'rows' & 'columns' (the variable names)
.value # openpyxl method to assign a value within a cell
 =  # assignment operator
f' # python declaration for the start of a f-String
row: # where is this from?
{row},  # what is this pointing to?
column: # where is this from?
{col} # what is this pointing to?
' # end of python f-string
thanks,
phil
'row:{row}, column:{col}' is string literal. It uses some basic string formatting. I.e. what is enclosed in curly brackets will change. Check https://docs.python.org/3/library/string...ing-syntax
from your enumeration - lines 7 and 9 are just example of text. It could be whatever you want.
lines 8 and 10 uses the f-string formatting to pass variables to string.
what about line 3?
(Oct-13-2018, 09:45 AM)pcsailor Wrote: [ -> ]what about line 3?

They come from those lines - in Python, you loop over iterables dicrectly, without indices
for row in rows:
  for col in columns:
ok, maybe I'm looking at this wrong.
I'm sorry if this is so basic. I feel pretty dumb right now >:

I thought with the f-string I would only have this code:
rows = range(1, 10)
columns = range(1, 5)
wb.active.cell(row, col).value = f'row:{row}, column:{col}'
and this code is not used:

for row in rows:
  for col in columns:
    wb.active.cell(row, col).value = 'fString_forLoop'
thanks,
Phil
(Oct-13-2018, 09:55 AM)pcsailor Wrote: [ -> ]ok, maybe I'm looking at this wrong.
I'm sorry if this is so basic. I feel pretty dumb right now >:

I thought with the f-string I would only have this code:
rows = range(1, 10)
columns = range(1, 5)
wb.active.cell(row, col).value = f'row:{row}, column:{col}'

You can process tables as a whole in pandas/numpy - though building initial values may still require either looping or comprehension (comprehension being a looping in not so deceiving disguise)