Top | Previous | Next |
String Formatting |
String formatting is a somewhat minor feature of Python, but turns out to be incredibly useful in Ignition. String formatting is used to manipulate strings, specifically to insert the values of variables inside a string without a bunch of concatenation.
The % operator is used in Python not just for modulus, but also for string formatting. Suppose we wanted to print a weather report. We could use concatenation, like this:
temp = 65.8 city = "Sacramento" windSpeed = 25 windDir = "east"
print city print "Weather: " + str(temp) + "°F, wind "+ str(windSpeed) + "mph from the "+ windDir
Yuck! This kind of concatenation is really a pain to write and to read. With string formatting, we could have written it like this:
temp = 65.8 city = "Sacramento" windSpeed = 25 windDir = "east"
print "%s weather: %f°F, wind %dmph from the %s" % (city, temp, windSpeed, windDir)
Ah, that's much easier on the eyes. What is happening here is that the % operator is applying the variables on its right-hand side to the format string on its left-hand side. It looks for placeholders (called format specifiers) inside the format string, and replaces them with corresponding values from the variables on the right-hand side. There are various format specifiers that can be used for different types of variable types. If you actually want a % sign inside the final string, use the special format specifier: "%%"
You can also put some extra information in the format specifiers between the % and the format specifier character. The most useful thing to do is to specify the number of decimal places to use to print floating point numbers. For example, "%.3f" would always put three digits after the decimal point. |