Python Forum
For loop (adding strings to a list trouble)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For loop (adding strings to a list trouble)
#1
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']
Reply
#2
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.
Reply
#3
'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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to read module/class from list of strings? popular_dog 1 466 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  trouble reading string/module from excel as a list popular_dog 0 413 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  Trying to understand strings and lists of strings Konstantin23 2 752 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  problem in using int() with a list of strings akbarza 4 685 Jul-19-2023, 06:46 PM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,506 May-01-2023, 09:06 PM
Last Post: deanhystad
  Adding values with reduce() function from the list of tuples kinimod 10 2,623 Jan-24-2023, 08:22 AM
Last Post: perfringo
  Help with Logical error processing List of strings dmc8300 3 1,076 Nov-27-2022, 04:10 PM
Last Post: Larz60+
  Help adding a loop inside a loop Extra 31 4,466 Oct-23-2022, 12:16 AM
Last Post: Extra
  Splitting strings in list of strings jesse68 3 1,748 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Adding a list to Python Emailing Script Cknutson575 4 2,299 Feb-18-2021, 09:13 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020