0

Python 2.6x

I have the following code:

hobbies = []

# Add your code elow!
for i in range(3):
    hobbies.append(raw_input("Enter a value : "))

print hobbies

It's generating the following output, if I enter the values as:

Enter a value :  1
Enter a value :  abcd
Enter a value :  a giga aks
[u'1', u'abcd', u'a giga aks']

I know that if I wrap str() around raw_input(..) then, print statement on list hobbies will print it successfully i.e. without "u" character in front of every list value.

I tried print str(hobbies) but it's still printing "u" as a prefix for every list value. If raw_input() returns a string type, then it should successfully add the entered values to the list which seems like it did but still printing "u" is something I'm not able to understand why.

Why it's printing "u"?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
AKS
  • 16,482
  • 43
  • 166
  • 258
  • 2
    Because you have `unicode` string objects. – Martijn Pieters Aug 05 '16 at 11:11
  • 1
    Try `print hobbies[0]` to write the *value* of one of those objects; you are printing the list, which produces a debug-optimised representation that makes it possible to reproduce the exact list contents. – Martijn Pieters Aug 05 '16 at 11:13
  • Thanks. Sorry I didn't checked enough. Docs mentioned that raw_input() returns a string but didn't clarify it. I see the other post (as Kasramvd mentioned) and using: hobbies.append(raw_input("Enter a value : ").encode('utf-8')) solved the issue. – AKS Aug 05 '16 at 11:24
  • Yes, sorry, I was intrigued by `raw_input()` return `unicode` objects but then had to relocate to another room before I could investigate. Looks like Kasramvd is spot-on on the dupe here. – Martijn Pieters Aug 05 '16 at 11:27
  • @MartijnPieters so printing individual [i] elements printed successfully but on individual lines i.e. when I used to print all index values inside a loop. I'll check how python can print values in the same line for multiple runs of a loop i.e. echo -n "value " in BASH. OK found it, print hobbies[i], (comma at the end) did print each index values in the SAME line when I used the loop to print each list value. – AKS Aug 05 '16 at 11:29

0 Answers0