raw_input


#1



Can someone explain why the str() is needed since the raw_input function returns as string already?


hobbies = []

# Add your code below!
for user_hobby in range(3):
    user_hobby = str(raw_input("What is your hobby: "))
    hobbies.append(user_hobby)
    print hobbies


#2

Slight modification to your code:

hobbies = []
for user_hobby in range(3):
    user_hobby = raw_input("What is your hobby: ")
    print type(user_hobby)
    hobbies.append(user_hobby)
    print hobbies

oops, raw_input does not seem to be a string, but rather a unicode


#3

can u explain further? When i did not put the str(), every item in the list will have a u something


#4

That is because it is unicode (u of unicode):

unicode('abcdef')

gives as output:

u'abcdef'

Which is why you cast it to a string using str()


#5

oh okay i see. Then how do u know when to use str()? sometimes printing list will print normally


#6

Well, if it prints normally it is usually a string. The moment i write some code:

start = "hello world"
print start

i know start contains a string (since i wrote it), but the moment i fetch input (with for example raw_input, or from the web) i would check which data type i am dealing with (using type()).

You can just temporary add a type() function, to check what you are dealing with, and then remove it, since most likely this won't change. You now know that raw_input gives unicodes, so you now know (or write it down) that raw_input gives unicode


#7

Thank You for your clear explaination! :slight_smile: