tags:

views:

206

answers:

5

I've seen the % operator being used in some Python code related to strings, such as:

String = "Value: " % variable

What does that mean? How is it different from using:

String = "Value: " + variable
+9  A: 

its for inserting values into strings containing format specifications

string = "number is %d" % 1

or

string = "float is %.3f" % 3.1425

this works in a similar way as spintf in C

You can insert multiple values in two ways:

string = "number %d and float %f" % (1,3.1415)
string = "number %(mynum)d and float %(myfloat)f" % {'mynum':1,'myfloat':3.1415}
Evgeny
Reference: http://docs.python.org/library/stdtypes.html#string-formatting-operations
S.Lott
Thanks! That works!
samoz
+2  A: 

The % is the string formatting operator (also known as the interpolation operator), see http://docs.python.org/library/stdtypes.html#string-formatting

las3rjock
A: 

Read formatting strings

  • '%' is the formatting string operator
  • '+' would be the concat operator
Agathe
+2  A: 

For strings % is the formatting operator. It also marks the start of the format specifier.

The + operator will concat a string at the end of the string with the right hand side of the +. The % operator will replace the format specifier in a formatted way at the location of the format specifier.

For numbers % is the modula operator. (Remainder)

Brian R. Bondy
A: 

According to John E. Grayson in his book "Python and Tkinter Programming", using string formatter rather than concatenation could increase the performance for at least 25 percent.

a = x + ' ' + y + ' ' + z

is 25 percent slower than

a = '%s %s %s' % (x, y, z)

In Python 3, you could also do like this:

a = '{} {} {}'.format(x, y, z)

Selinap