Print list using python

I have a list compiled from excel cells using python - say listlist . Each item in a cell / list is in Unicode. When I print the list as

 print listlist 

I see that 'u' is being added to each member of the list. But when I print a list like

 for member in listlist: print member 

I do not see the "u" added to the member.

Can someone explain to me why there is such a difference? Is it defined in the xlrd module?

+4
source share
4 answers

This is because print list equivalent to

 print "[", ", ".join(repr(i) for i in list), "]" 

repr(s) is u"blabla" for the unicode string, and print s prints only blabla .

+6
source

When printing a list, it displays each object in the list using the __repr__ object

When printing an object alone, it uses the __str__ object

+4
source

There are two ways to turn a Python value into a string str and repr (and their equivalent class __str__ and __repr__ ). The difference comes from these two functions. From a Python tutorial :

The str () function is designed to return representations of values ​​that are readable enough for humans, and the repr () function is designed to generate representations that can be read by the interpreter (or will throw SyntaxError if there is no equivalent syntax).

The print statement calls str object you are going to, but the list __str__ method calls repr on it. The values ​​in your list are unicode strings. In a human-readable form, a unicode person is inappropriate, so you don't get u marks or even quotation marks. In machine-readable form, this is important, so u included.

+3
source

when you print a list, python prints a list view.

the standard representation of the list is to print the square brackets of the opening ( [ ), then the representation of each element is separated by a comma ( , ) closing the square bracket ( ] ). (more precisely, the representation of an object is what is returned when its member __repr__() ) is called). note that the standard unicode string representation is u'...' .

now when you print the string, you are not printing the string representation, you are printing the string (the value returned by calling the __str__() member). and the string does not include formatting characters such as Unicode flags, quotation marks, etc.

+1
source

Source: https://habr.com/ru/post/1344581/


All Articles