0

For example given the following for loop:

for i in range(3):
    print(i, '->',i+1)

Gives the output:

0 -> 1
1 -> 2
2 -> 3

How could I save this output in string form such that it is saved in a variable.

So for example could say print(my_variable) and the output is as the above output.

Edit Given the following list:

[['ORGANIZATION', 'EDUCATION', 'UniversityWon', 'FormMathematics'], ['PERSON', 'Sixth', 'Economics'], ['GPE', 'FrenchUK', 'London']]

I have the following for loop that prints them in the desired way:

for i in output:
    print(i[0], '->', ', '.join(i[1:]))

Output of:

ORGANIZATION -> EDUCATION, UniversityWon, FormMathematics
PERSON -> Sixth, Economics
GPE -> FrenchUK, London

How can i save this output into a variable such that if i executed print(variable), the above output would be printed?

4
  • Sound like an x/y problem. Could you edit your post with some details about why you want to do this? Commented Mar 10, 2022 at 16:18
  • That would require a lot of other code which doesn't really add explanation to the problem at hand. Commented Mar 10, 2022 at 16:18
  • you may be looking for string interpolation, which is often done with an f-string or the .format() method Commented Mar 10, 2022 at 16:19
  • 2
    "\n".join(f'{i} -> {i + 1}' for i in range(3)) Commented Mar 10, 2022 at 16:20

2 Answers 2

1

A list comprehension can be used to generate the individual strings.

[f"{i} -> {i + 1}" for i in range(3)]

We can then join those with newlines.

"\n".join([f"{i} -> {i + 1}" for i in range(3)])

But we don't need to use a list comprehension here. A generator expression will be more efficient as it doesn't generate an entire list first and then iterate over that list.

"\n".join(f"{i} -> {i + 1}" for i in range(3))

If every line need to end in a newline, you can factor that into the f-string and then join them with an empty string.

''.join(f"{i} -> {i + 1}\n" for i in range(3))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help, i have updated the question if you could take a look that would be great.
The concepts already shown can be used to accomplish that additional task.
I am not sure how to include the join within {} since this throws an error
0

You can use an f-string like this:

result = ""

for i in range(3):
    result += f"{i} -> {i + 1}\n"

print(result)

1 Comment

Thanks for the help, i have updated the question if you could take a look that would be great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.