21 Mar, 2010

Sprintf Function in Python

The printf or sprintf function is used to format strings in PHP and C programming constructs. sprintf in php returns the formatted string whereas printf just prints the output.

$variable = sprintf("%d %s %d = %d",4,"+",5,9);
print $variable;
//OR
printf("%d %s %d = %d",4,"+",5,9);

//Both lines are identical.
//Prints 4 + 5 = 9

On python, sprintf is handled using an operator instead of function. The % operator on a string does formatting.

var = '%d %s %d = %d' % (4,'+',5,9)

The above code assigns var = "4 + 5 = 9"

Install Python for Nokia E63 / E71 compatible symbian phones and code on the move Python rocks :)


Comments (1) Post a comment
  • multi line hear doc strings format

    Can multi line hear doc strings use this ? Like
    s = """ 
    name : %s
    address: %s
    phone: %d
    mortgage amount: %d
    """%(name,address,phone,mortgage_amount)
    
    By newguy on 07 Dec, 2011 Reply
You may also like



Email Newsletter
Email:
Popular Posts
Recent Posts
Tags
Random photo
Elephant Beach at Havelock Island Elephant Beach at Havelock Island in Havelock Island Andaman
On Facebook
Recent Comments


digitalpbk