我想将打印输出分配给某个字符串变量
print "Cell:", nei, "from the neighbour list of the Cell:",cell,"does not exist"
你可以请一下建议吗?
答案 0 :(得分:3)
使用简单的字符串连接:
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)
答案 1 :(得分:0)
这不是Python的工作方式。如果您 NOT 有足够的理由,请尽量使用=
。
但如果你坚持,你可能会这样做。(同样,这是非常不必要的)
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})