0

I have this variable called var1:

var1 = tweet[0]["id_str"]

When I just type var1 on the console, this is the output:

>>> var1
u'528427823468642304'

But, then I print var1, this is the output:

>>> print var1
528427823468642304

Why are the outputs different? I need only the numbers, without the single quotes or the letter u, but the two different outputs are confusing me..

  • possible duplicate of [Difference between \_\_str\_\_ and \_\_repr\_\_ in Python](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) – tripleee Nov 01 '14 at 07:12

2 Answers2

1

The u' prefix indicates that the object in question is a unicode string. This is automatically removed when you print a variable. You don't have to worry about the u' portion appearing if you try to use or index the string.

At risk of seeming a little snarky (which I don't intend), it seems pretty clear that you didn't actually try to use var1 in any sense. If you'd tried:

 print(var1[0])

you'd have realized that the first index of the string itself was 5.

And if you'd tried:

 print(var1 == '528427823468642304')

you'd have seen True. Either way you would've realized that the u' prefix had no bearing on the way you could use the string. To boot, you could have just googled "python u prefix" and the first result would have told you exactly what you needed to know. This isn't to say categorically that you shouldn't ask questions on SO that someone's already asked somewhere on the internet, just that my experience is that knowing to search for the specifics of your problem before spending the time to ask a question about it will generally lead to quicker learning.

furkle
  • 5,019
  • 1
  • 15
  • 24
  • Thank you. Printing `(var1[0])` or trying `print(var1 == '528427823468642304')` to see if that was the real content of the variable didn't cross my mind. I will use that kind of technique on my own for now on before asking questions. – Vince Vinegar Nov 01 '14 at 21:41
  • @VinceVinegar Don't be worried to ask questions. It really wasn't an imposition - I got 25 reputation from it - my point is mostly just that you'll learn more quickly, and get more programming done, if you find pre-existing answers rather than spending the non-negligible amount of time it takes to ask a question on SO. Best of luck. – furkle Nov 01 '14 at 21:42
0

The character u shows that this is a unicode string. If you want the actual number you can perform int(var1) on it to convert it to an integer.

k-nut
  • 3,447
  • 2
  • 18
  • 28