Masthead

Formatting Strings

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. Controlling the number of digits produced by 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. You can also add a "format specification" to the function call. This is shown with ".2" in the code below:

print("Value: "+format(0.12345,".2")) # only prints two digits

You can change the number of digits by changing the value after the period. Try the following:

print("Two digits: "+format(12345.6789,".2"))
print("Four digits: "+format(12345.6789,".4"))
print("Six digits: "+format(12345.6789,".6"))
print("Eight digits: "+format(12345.6789,".8"))
print("Twelve digits: "+format(12345.6789,".12"))
print("Fourteen digits: "+format(12345.6789,".14"))
print("Sixteen digits: "+format(12345.6789,".16"))

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: "+format(12345.6789,".2f")) 

Formatting Numbers (optional)

You can specify a number before the period to specify the total number of digits to display.

print("Minimum of ten characters: "+format(12345.6789,"10.2f"))
 

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: }"+format(12345.6789,"0<10.2f")) 

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*1.2
print(format(value,"0<10")+" "+format(value,">10")+" "+format(value,"^10"))
count=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 (optional)

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(format(count,"d")+" "+format(count,"x")+" "+format(count,"b"))
 count+=1

4. Formatting Percentages (optional)

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: "+format(12.34,".4%"))

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: "+format(Latitude,"0.7")+"\xB0 N, "+format(Longitude,"0.7")+"\xB0 W")
Note: The "format()" function is replacing the older "%" operator for formatting strings.

When you write out coordinates in DMS (degrees, minutes, and seconds), you'll probably want to add the degree symbol for degrees, a single quote for the minutes and a double quote for the sectons. It is a bit tricky to add the double quote as you need to end up with two double-quotes in the CSV file so that ArcMap (see below):

Diagram of adding double quotes within a string for ArcMap

Additional Resources

An Introduction to Python: 3.1.2 Strings

ASCII Reference Table

© Copyright 2018 HSU - All rights reserved.