Formatting Strings
In Review
1. Strings
Strings are text just like what you are currently reading and are very different from the numbers we've been working with so far. A string is a sequence of 'characters'. These characters can be from the alphabet, numeric digits, punctuation, or one of a number of 'special characters' we'll learn more about in just a bit.
You've already worked with strings a little when you printed "Hello World". The quotes indicate that "Hello World" is a string instead of a number. Each of the letters, 'H', 'e', 'l', and so on, are the individual characters in the string. Python allows us to manipulate strings in a variety of ways. You can combine strings together, by using the "+" symbol as in:
print("This is a website" + " " + "dedicated to Python programming")
You can also include numbers in strings but you need to convert them to a string using the build-in "format()" function. Let's say we want to output a number but also have a nice message to go with it. Try the following:
x=pow(9,2) print("Nine squared is: "+format(x))
The "pow()" function is a built-in function for raising one number, 9 in this case, to the power of another number, 2 in this example. The "print()" function we have used before to output strings to the console and the "format()" function will convert anything passed to it into a string. This means the value of x, or 81, will be converted to a string, "81". The plus operator ("+") will then "concatenate" the "Nine squared is: " string with the "81" string and give us our output:
Nine squared is: 81
Just the ability to concatenate strings with the plus ("+") operator and the "format()" function give us a great deal of flexibility in creating strings. Right now we're using them to just write to the console but later we'll use them to write formatted text files and web services.
String can be "constant" or in a variable. In the example above, "x" was a variable for a number. Below we are using "FirstName" and "LastName" as string variables:
FirstName="John" LastName="Doe" FullName=FirstName+LastName print(FullName)
Try this and see what happens. We need to add a space between the names to make it more readable. Try the code below:
FirstName="John" LastName="Doe" FullName=FirstName+" "+LastName print(FullName)
The " " could be replaced with a dash or anything else you like. You can also change the output to be "LastName, FirstName". Think of the possibilities! Try some now.
2. The format() function
Above you saw that the "format()" function can convert a number into a string. This function is actually very powerful and can be used to create very complex strings. The way this works is to create a string and then add the "format()" function at the end of it after a period ("."). The string needs to have a "format specification" within it. These are within braces as shown below:
print("Values: {0},{1},{2}".format(0.12345,12345,12.345))
Execute the line above in Wingware and you should see each of the numbers printed as shown. The number inside the braces indicates which value to use from within the parenthesis after the "format". If you're wondering about the syntax, whenever you create a string, Python converts it to a "string class". The "format" is a function in the string class and the values are passed into that function as parameters. We'll learn more about this later.
The "format" function is very flexible and will print out any value in a reasonable default way. You can also take full control of how values are printed out. Placing a colon, a period, and then a number after the first number in the braces allows you to specify the number of digits you want to see printed for floating point numbers. Try the following:
print("Two digits: {0:.2}".format(12345.6789))
print("Four digits: {0:.4}".format(12345.6789))
print("Six digits: {0:.6}".format(12345.6789))
print("Eight digits: {0:.8}".format(12345.6789))
print("Twelve digits: {0:.12}".format(12345.6789))
print("Fourteen digits: {0:.14}".format(12345.6789))
print("Sixteen digits: {0:.16}".format(12345.6789))
Notice that Python will automatically convert the values to scientific notation when needed. It will also only print the number of valid digits in the number. If you want to prevent this, just add an 'f' to the specification. The value after the period then specifies the number of digits to print after the decimal point.
print("Two digits after the decimal: {0:.2f}".format(12345.6789))
You can specify a number before the period to specify the total number of digits to display.
print("Minimum of ten characters: {0:10.2f}".format(12345.6789))
You'll see that Python added spaces before the number. You can change it to extend the number on the right by specifying the "alignment" to right with a less than sign ("<") preceded by a fill character.
print("Minimum of ten characters: {0:0<10.2f}".format(12345.6789))
You can provide any character you like for the fill character and you can center numbers by using a caret ("^") instead of the less than sign. Spend a little time playing with different outputs and even try printing a table of numbers. The code below will print a simple table with the numbers aligned left, right, and center.
count=0 while (count<10): value=count*12345.6789 print("{0:0<10} {1:>10} {2:^10}".format(value,value,value)) count+=1
You now know most of what you'll need to know to format strings from Python. Check the bottom of this page for additional information including the full specification for the format function.
3. Different bases
When a number is stored in a computer it's stored in "binary" (base 2). The format function allows you to display numbers in a variety of bases. Use the code below to print values 0 through 15 in the three most commonly used bases; decimal, hexadecimal (base 16), and binary.
count=0 while (count<16): print("{0:d} {1:x} {2:b}".format(count,count,count)) count+=1
4. Formatting Percentages
Python provides a special printing of percentages. By adding a percent just before the end of the format specification, Python will automatically convert the number to a percent.
print("Percent: {0:.4%}".format(12.34))
5. Formatting Coordinates
With what we've now learned, you can write out geographic coordinates exactly how you want to. Below is code to display a decimal degree coordinate as longitude and latitude with 7 digits.
Latitude=40.12345 Longitude=-105.12345 print("Coordinate: {0:.7}N,{1:.7}W".format(Latitude,Longitude))
Warning: The online Python documentation is based on Python 3.1 (currently). This version does not require you to specify the "format specifier". If you are using an older version of Python (ArcGIS ships Python 2.7) you will need to specify the value before the colon.