anc1revv
anc1revv

Reputation: 1623

Typecasting to unicode string?

I'm going through the djangobook and in one of the examples the author writes this:

def __unicode__(self):
      return u'%s %s' % (self.first_name, self.last_name)

Does the "u" in front of '%s %s' turn the string into unicode?

Upvotes: 0

Views: 332

Answers (3)

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16367

Yes, that u prefix means that the string is Unicode. There is one more thing to know - you should declare the source code encoding so that Python knows how to deal with the string:

http://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code

Correct way to define Python source code encoding

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308402

The % operator will create a new string using the given string as a format. Since you've used a leading u this string will be Unicode. Each %s will cause the argument to be converted into Unicode as well before it is inserted into the new string.

Upvotes: 1

Dhara
Dhara

Reputation: 6767

It doesn't quite 'turn' the string to unicode, it represents a unicode-string. To quote the documentation

In Python source code, Unicode literals are written as strings prefixed with the ‘u’ or ‘U’ character ... Ideally, you’d want to be able to write literals in your language’s natural encoding. You could then edit Python source code with your favorite editor which would display the accented characters naturally, and have the right characters used at runtime.

Upvotes: 3

Related Questions