What is the equivalent of php's print_r() in python?
Or is there a better way to quickly output the contents of an array 开发者_运维知识库(multidimensional or what not). Thanks.
The python print statement does a good job of formatting multidimesion arrays without requiring the print_r available in php.
As the definition for print states that each object is converted to a string, and as simple arrays print a '[' followed by a comma separated list of object values followed by a ']', this will work for any depth and shape of arrays.
For example
>>> x = [[1,2,3],[4,5,6]]
>>> print x
[[1, 2, 3], [4, 5, 6]]
If you need more advanced formatting than this, AJs answer suggesting pprint is probably the way to go.
You were looking for the repr
bult-in function.
http://docs.python.org/2/library/functions.html#func-repr
print repr(variable)
In Python 3, print
is no longer a statement, so that would be:
print( repr(variable) )
from pprint import pprint
student = {'Student1': { 'Age':10, 'Roll':1 },
'Student2': { 'Age':12, 'Roll':2 },
'Student3': { 'Age':11, 'Roll':3 },
'Student4': { 'Age':13, 'Roll':4 },
'Student5': { 'Age':10, 'Roll':5 }
}
pprint(student)
here's one you can try:
https://github.com/sha256/python-var-dump
you can install it simply using pip
pip install var_dump
disclaimer: I wrote it :)
print
and pprint
are great for built-in data types or classes which define a sane object representation. If you want a full dump of arbitrary objects, you'll have to roll your own. That is not that hard: simply create a recursive function with the base case being any non-container built-in data type, and the recursive case applying the function to each item of a container or each attribute of the object, which can be gotten using dir()
or the inspect
module.
there is print_r for python https://github.com/marcbelmont/python-print_r/wiki but it is better to use standard modules
my_list = list(enumerate([1,2,3,4,5,6,7,8,9],0))
print(my_list)
Will print [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
if you want to format variable
as a string you can do:
s = repr(variable)
it works regardless the type, and doesn't requiere any imports.
If you want to include the contents of an object in a single string together with its type:
if hasattr(variable, "__dict__"):
s = "{}: {}".format(variable, vars(variable))
else:
s = repr(variable)
For simple test views I use HttpResponse. Testing request from form, variable, string, id, not Object
from django.http.response import HttpResponse
HttpResponse(variable)
def add_comment(request, id):
return HttpResponse(id)
精彩评论