0

I was printing output in an iteration using a for loop in the following format.

print(fname, "[", line_no, ",", index, "] ", line, sep="")

But, for some reason, Now I have to print the whole output in a single variable. How do I make it work ? Do I have to use list ? If yes then how ?

sodmzs
  • 184
  • 1
  • 16

1 Answers1

2

You can use string formatting to assign your formatted string to a variable and print it

Example using f-strings for python>=3.6

s = f'{fname} [{line_no},{index}] {line}'
print(s)

Or using string.format

s = '{} [{},{}] {}'.format(fname, line_no, index, line)
print(s)

To collect all this in a string via a for loop, you can use a list to collect the strings, and join and print them outside the loop

#List to collect strings
li = []

#Iterate through for loop and add all strings to list
for foo in blah:
    s = f'{fname} [{line_no},{index}] {line}'
    li.append(s)

#Join list to string and print it
res = ' '.join(li)
print(res)
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • Sorry for misunderstandings.`print(fname, "[", line_no, ",", index, "] ", line, sep="")` This prints the output for each iteration. And I want to store all the output in a single variable. Thanks – sodmzs Jun 19 '19 at 20:37