For Your Hobbies. Expanded Help


#1



Hi there, I was able to sucessfully complete lesson #14, but I started playing around with the code and noticed something peculiar.


For Your Hobbies


The print of the list 'hobbies' returns [u'Woodworking', u'Trading.... etc.

Name a hobby: Woodworking
Name a hobby: Trading
Name a hobby: Learning
[u'Woodworking', u'Trading', u'Learning']
Your favorite hobby is Woodworking
Your favorite hobby is Trading
Your favorite hobby is Learning
None


I don't understand where the u is coming from, and when I print out 'for each' the u is gone.


hobbies = []

for i in range(3):
    hobbies.append(raw_input("Name a hobby: "))
    
print hobbies

for hobby in hobbies:
    print "Your favorite hobby is %s" % hobby


#2

raw_input() returns strings as encoded by the operating system or the environment. So in the different environment, you might get a different result.

This u placed before the string is an indicator that this is a Unicode string.

What does it change? Well, let's say that I want to store my favourite food in the variable. But I create this application for my friends so I will write this string in Polish.

favourite_food = "pączki"
print favourite_food
=> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 1: ordinal not in range(128)

Ok, I got the error, because Python does not know how to decode the ą. To make sure that Python will treat my string in the correct way I can mark it as a Unicode string:

favourite_food = u"pączki"
print favourite_food
=> pączki

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.