Python print_r返回值而不是打印它

Ric*_*nop 1 python

在Python中,是否有可能做类似的事情:

echo 'Content of $var is ', print_r($var, TRUE);
Run Code Online (Sandbox Code Playgroud)

用PHP?

我有一个变量var,我想以可读的形式将其内容分配给字符串,例如:

str = 'Hello. '
str = str + var
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 6

你可以简单地使用str(var),如:

s = 'Hello. ' + str(var)
Run Code Online (Sandbox Code Playgroud)

这里str是一个内置函数,与str脚本中的内容无关.在Python中编码时,请避免使用与内置函数名称一致的名称.

另一种方法是使用字符串格式化运算符%:

s = 'Hello. %s' % var
Run Code Online (Sandbox Code Playgroud)


Tad*_*eck 5

实现你想要的三种方法

在python中至少有三种方法:

  1. 最好的一个 - 使用.format()字符串对象的方法(自Python 2.6起可用):

    使用简单的替换:

    print 'Content of var is {}'.format(var)
    
    Run Code Online (Sandbox Code Playgroud)

    使用名称引用:

    print 'Content of var is {var}'.format(**locals())
    
    Run Code Online (Sandbox Code Playgroud)
  2. 始终工作的一个- 格式化操作:

    使用简单的替换:

    print 'Content of var is %s' % var
    
    Run Code Online (Sandbox Code Playgroud)

    使用名称引用:

    print 'Content of var is %(var)s' % locals()
    
    Run Code Online (Sandbox Code Playgroud)
  3. 连接:

    print 'Content of var is ' + str(var)
    
    Run Code Online (Sandbox Code Playgroud)

格式化操作之间%r和之间的区别%s

%r不同于%s,因为%r被替换为变量的表示,并被%s替换为转换为字符串的变量.您可以在下面的示例中清楚地看到它:

>>> class MyClass():
    def __str__(self):
        return '__str__() result'
    def __repr__(self):
        return '__repr__() result'


>>> mc = MyClass()
>>> '%r' % mc
'__repr__() result'
>>> '%s' % mc
'__str__() result'
Run Code Online (Sandbox Code Playgroud)

它有帮助吗?