Python打印输出到variab

2024-05-17 18:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将打印输出分配给一些字符串变量

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

你能给我个建议吗?


Tags: ofthe字符串fromnotcell建议list
2条回答

使用简单字符串连接:

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

或字符串格式:

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

这不是Python的工作方式。如果您没有足够的理由,请简单地使用=。 但是如果你坚持的话,你可以这样做

    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")

如果您只是尝试将事物连接成一个字符串,则可以使用多种方法:

  • 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})

看看python's string formatingpython's str

相关问题 更多 >