Home > Net >  How do I assign output of a function to a string variable?
How do I assign output of a function to a string variable?

Time:01-29

I'm trying to create a 3 x 3 board with number from 1-9 with this function:

board =(1,2,3,4,5,6,7,8,9)
def board_display():
    print("_" *6)
    for row in range(3):
        print("".join((f"|{board[row*3  position]}" for position in range(3)))   "|")
        print("_" *6)
board_display()

Output:

|1|2|3|
______
|4|5|6|
______
|7|8|9|
______

Now I want to assign this board to a variable, say "New_board", so that I can use this variable in other functions. How can I do that?

CodePudding user response:

Try this:

board='\n'.join(['|' '|'.join(map(str,range(1 3*j,4 3*j))) '|\n' '-'*6
                 for j in range(3)])

This is the result:

>>> print(board)
|1|2|3|
------
|4|5|6|
------
|7|8|9|
------

CodePudding user response:

If possible you should simply append all lines to a list and then join it with newlines (as to mimic the behaviour of print()). Like this:

def board_display():
    res = []
    res.append("_" *6)
    for row in range(3):
        res.append("".join((f"|{board[row*3  position]}" for position in range(3)))   "|")
        res.append("_" *6)

    return "\n".join(res)

Although I highly advice against it, you could use redirect_stdout() from contextlib. Then your code would look like this:

import io
from contextlib import redirect_stdout

res = io.StringIO()
with redirect_stdout(res):
   board_display()

output = res.getvalue()  # Turn the StringIO() into 'str'

Like I said though, you should definitely use the previously mentioned method (since you are able to modify the function) - but take this as a fun fact and hidden gem in the standard library

  •  Tags:  
  • Related