-1

I would like to assign print output to some string variable

print "Cell:", nei, "from the neighbour list of the Cell:",cell,"does not exist"

Could you please advice?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ussrback
  • 491
  • 2
  • 8
  • 22

2 Answers2

3

Use simple string concatenation:

variable = "Cell: " + str(nei) + " from the neighbour list of the Cell: " + str(cell) + " does not exist"

or string formatting:

variable = "Cell: {0} from the neighbour list of the Cell: {1} does not exist".format(nei, cell)
semptic
  • 645
  • 4
  • 15
0

It's not the way Python works. If you do NOT have enough reason, simpliy use =. But if you insist, you may do like this.(Again, it's very unnecessary)

    def printf(*args):
        together = ''.join(map(str, args))    # avoid the arg is not str
        print together
        return together
    x = printf("Cell:", nei, "from the neighbour list of the Cell:",cell,"does not exist")

If you are only try to join things into a string, there are many ways you can do:

  • x = ''.join(("Cell:", str(nei), "from the neighbour list of the Cell:",str(cell),"does not exist"))
  • x = "Cell:%s from the neighbour list of the Cell:%s"%(nei, cell)
  • x = "Cell:{} from the neighbour list of the Cell:{}".format(nei, cell)
  • x = "Cell:{key_nei} from the neighbour list of the Cell:{key_cell}".format({'key_nei':nei, 'key_cell':cell})

have a look at python's string formating and python's str

TylerTemp
  • 970
  • 1
  • 9
  • 9
  • @ussrback Not very clear about your question. If want to write print output into a file, Have a look at [python redirect output to file](http://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python). If you want to write to a csv file with csv module, you need to control it by yourself – TylerTemp Aug 26 '14 at 12:05