Python Forum

Full Version: For loop (adding strings to a list trouble)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
When I run the following code, the user is asked 3 times "Name a hobby: ", so I enter fishing, hiking, coding then hit enter. When I then print the list hobbies, each item in the list has a u" in it. What is this and what am I doing that is putting it there?

hobbies = []

for i in range(3):
  hobby = raw_input("Name a hobby: ")
  hobbies.append(hobby)
  
print hobbies
The result of running the code is the following:

Name a hobby: fishing
Name a hobby: hiking
Name a hobby: coding
[u'fishing', u'hiking', u'coding']
the u stands for Unicode.
My suggestion to eliminate this (and many other Unicode bothers that appear) is to upgrade to python 3. Python 3.7.0 to be more precise.
'u' prefix shows only when you don't print a string object directly, and print the containing object. Printing string elements of a list one-by-one will eliminate this issue - or
print ', '.join(hobbies) 
Either way, regardless of the Python version you use, printing lists "as is" adds redundant symbols like square brackets and quotes to your output