Print string print 'u' before string in Python?

'u' before items in a printed list? I did not enter u in my code.

hobbies = []

#prompt user three times for hobbies
for i in range(3):
    hobby = raw_input('Enter a hobby:')
    hobbies.append(hobby)

#print list stored in hobbies
print hobbies

When I run this, it prints a list, but it is formatted as follows:

Enter a hobby: Painting
Enter a hobby: Stargazing
Enter a hobby: Reading
[u'Painting', u'Stargazing', u'Reading']
None

Where did these "u" come from each list item?

+4
source share
4 answers

I think that you are really surprised that printing a single line does not do the same as printing a list of lines, and it is true whether they are Unicode or not:

>>> hobby1 = u'Dizziness'
>>> hobby2 = u'Vรฉrtigo'
>>> hobbies = [hobby1, hobby2]
>>> print hobby1
Dizziness
>>> print hobbies
[u'Dizziness', u'V\xe9rtigo']

u , , . str unicode, escape- ( mojibake, ... , ).


Python : , , str , , repr. Painting 'Painting', . Unicode Painting u'Painting'.

print str, print hobby1 Painting ( u, Unicode).

str repr , str. , hobbies, ( a u, Unicode).

, , , . [foo, bar, baz] - , ? , , , , . My hobbies are [Painting, Stargazing] , My hobbies are ['Painting', 'Stargazing']. , - , .

, , , :

>>> print 'Hobbies:', ', '.join(hobbies)
Hobbies: Painting, Stargazing

, Unicode:

>>> print u'Hobbies:', u', '.join(hobbies)
Hobbies: Painting, Stargazing
+10

, , .

for hobby in hobbies:
  print hobby
+6

"u" is not part of the string, but indicates that the string is a unicode string.

+5
source

If you want to convert unicode to string. You can just use str (unicodedString) or unicode (normalString) for another conversion method

code

hobbies = []

#prompt user three times for hobbies
for i in range(3):
    hobby = raw_input('Enter a hobby:')
    # converting the normal string to unicode
    hobbies.append(unicode(hobby))

# Printing the unicoded string
print("Unicoded string")
print(hobbies)
hobbies = [str(items) for items in hobbies]

# Printing the converted string
print("Normal string from unicoded string")
print(hobbies)

Exit

Enter a hobby:test1
Enter a hobby:Test2
Enter a hobby:Test3

Unicoded string
[u'test1', u'Test2', u'Test3']

Normal string from unicoded string
['test1', 'Test2', 'Test3']
0
source

All Articles