Mike Van
Mike Van

Reputation: 21

What does %c character formatting do in Python and it's use?

Going through string formatting operations but can't exactly wrap my head about %c operation and its use.

Learn Python the Hard Way, gave the following example but it makes little sense without the proper context.

"%c" % 34 == '"'     

Here is the link to if anyone wants to check it out: http://learnpythonthehardway.org/book/ex37.html

Upvotes: 1

Views: 12612

Answers (3)

nu11p01n73R
nu11p01n73R

Reputation: 26677

The %c is a format character gives the character representation. For example consider the following statements

>>> print "%c" % 'a'
a
>>> print ("%c" % 97)
a
>>> print "%c" %'"'
"
>>> print "%c" %34
"
>>> print "%c" %'asdf'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %c requires int or char

Breaking up

"%c" % 34 == '"' 

would be like

>>> "%c" % 34
"
>> '"' == '"'
True

Upvotes: 1

Makoto
Makoto

Reputation: 106508

%c represents character values. It's part of the integer representation types.

You can't enter a value larger than an unsigned byte (255) as a positional argument to it, so be careful where and when you elect to use it.

Upvotes: 0

Loocid
Loocid

Reputation: 6451

It gives the character that is represented by the ASCII code "34".

If you look up an ASCII table you will notice that 34 = "

Upvotes: 4

Related Questions