Python 2.7 - Why does python encode a string when .append () is in a list?

My problem is String

# -*- coding: utf-8 -*- print ("################################") foo = "142.0000" print (type(foo)) print("foo: "+foo) foo_l = [] foo_l.append(foo) print ("List: " ) print (foo_l) print ("List decode: ") print([x.decode("UTF-8") for x in foo_l]) print("Pop: "+foo_l.pop()) 

Print result:

 ################################ <type 'str'> foo: 142.0000 List: ['\xd0\xa1\xd0\xa2142\xd0\x9d.0000'] List decode: [u'\u0421\u0422142\u041d.0000'] Pop: 142.0000 

This one works fine , I just write the line "CT142H.0000" manually using the keyboard (its same code)

 print ("################################") foo = "CT142H.0000" print(type(foo)) print("foo: "+foo) foo_l = [] foo_l.append(foo) print ("List: ") print (foo_l) print ("List decode: ") print([x.decode("UTF-8") for x in foo_l]) print("Pop: "+foo_l.pop()) 

Print result:

 ################################ <type 'str'> foo: CT142H.0000 List: ['CT142H.0000'] List decode: [u'CT142H.0000'] Pop: CT142H.0000 

Why does python encode the first line when I add it to the list?

-----------------------------------------------

This is currently resolved, I was worried about it, I put the β€œresult” in JSON and then on the website, finally on the website it works great!

-----------------------------------------------

I found another solution, but there is no right solution, because in some cases you will have problems.

 json.dumps(list, ensure_ascii=False) 

Thanks everyone!

+6
source share
1 answer

Because, although they look like regular C / T / H characters, they are actually not the same characters.

These are Cyrillic characters.

C - Cyrillic uppercase letter ES
T - Cyrillic Letter Capital TE
H - Cyrillic letter EN

You will need to check where these characters come from, why they are so.

Why they were printed using the view \x.. because when you print list , the __str__() method in the list is called, but the list itself calls __repr__() on its elements, and therefore you get an internal representation of the strings. You will get a similar result if you do this -

 print(repr(foo)) 

for the first case.

+11
source

All Articles