fString Nested forLoop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: fString Nested forLoop (/thread-13399.html) |
fString Nested forLoop - pcsailor - Oct-13-2018 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 RE: fString Nested forLoop - buran - Oct-13-2018 wb.active.cell(row, col).value = f'row:{row}, column:{col}' RE: fString Nested forLoop - pcsailor - Oct-13-2018 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-stringthanks, phil RE: fString Nested forLoop - buran - Oct-13-2018 '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.html#format-string-syntaxfrom 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. RE: fString Nested forLoop - pcsailor - Oct-13-2018 what about line 3? RE: fString Nested forLoop - volcano63 - Oct-13-2018 (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: RE: fString Nested forLoop - pcsailor - Oct-13-2018 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 RE: fString Nested forLoop - volcano63 - Oct-13-2018 (Oct-13-2018, 09:55 AM)pcsailor Wrote: ok, maybe I'm looking at this wrong. 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) |