Python:将打印输出分配给变量

时间:2021-06-26 21:45:41

I would like to know how to assign the output of the print function (or any function) to a variable. To give an example:

我想知道如何将print函数(或任何函数)的输出分配给变量。举个例子:

import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()

How do I assign the output of print tag.getArtist to a variable?

如何将print tag.getArtist的输出分配给变量?

3 个解决方案

#1


20  

The print statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:

Python中的print语句将其参数转换为字符串,并将这些字符串输出到stdout。要将字符串保存到变量,只需将其转换为字符串:

a = str(tag.getArtist())

#2


6  

probably you need one of str,repr or unicode functions

可能你需要str,repr或unicode函数之一

somevar = str(tag.getArtist())

depending which python shell are you using

取决于你使用的是哪个python shell

#3


4  

somevar = tag.getArtist()

http://docs.python.org/tutorial/index.html

http://docs.python.org/tutorial/index.html

#1


20  

The print statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:

Python中的print语句将其参数转换为字符串,并将这些字符串输出到stdout。要将字符串保存到变量,只需将其转换为字符串:

a = str(tag.getArtist())

#2


6  

probably you need one of str,repr or unicode functions

可能你需要str,repr或unicode函数之一

somevar = str(tag.getArtist())

depending which python shell are you using

取决于你使用的是哪个python shell

#3


4  

somevar = tag.getArtist()

http://docs.python.org/tutorial/index.html

http://docs.python.org/tutorial/index.html