Python Series Part 6: Printing Strings

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
364
Reaction score
403
Credits
13,257
There are a few ways to print strings to help make the process a little easier. We will look at a few ways to do this task.

No matter which way you choose is fine. Everyone may have a preference for a specific method.

To explain, there are four methods to print strings:
  1. Unformatted with or without separators
  2. Print formatting
  3. str.format
  4. f-string
Example Format

There are a few ways to do this. Let's print something using variables and strings.

For these examples, let's use the same variables and strings. So, we need something kind of like a form letter style we fill in specific variables. This will be like we will print a bunch of letters using information from a database to produce the same letter, but with specific information.

Let's try something like:

'Hello Mr. Jarret Buse,

We know you work for Linux.org.'

Of course, the letter would be longer, but we just need a quick example. The variables are:
  • Prefix - Mr., Mrs, Miss, Dr, etc.
  • First Name
  • Last Name
  • Workplace Name
Keep in mind that this is a very simple example. A genuine letter could include much more personal information.

Unformatted

We can just simply print the information with no type of formatting, such as:

Code:
prefix="Mr."
firstname="Jarret"
lastname="Buse"
workplace="Linux.org"

print ("Hello", prefix, firstname, lastname+",")
print ("We know you work for", workplace+".")

This method works well, but making a change can be a little troublesome if the example is longer. For some, this may be a little hard to read as code.

Let's explain a little here. Mixing strings with variables will print a space when separated by a comma(,). To not print a space, you can use a plus sign (+), as was done when using the comma after the name and the period at the end of the first sentence.

We use the commas as separators and use the space as the default separation method. You can specify a different separator by adding 'sep="<character>"' at the end of the line. For example, we could separate each string and variable with an underscore (_):

Code:
print ("Hello", prefix, firstname, lastname+",",sep="_")
print ("We know you work for", workplace+".",sep="_")

The output would be:

Hello_Mr._Jarret_Buse,
We know you work for_Linux.org.


As you can see, the underscores only appear when there is a comma being used to separate a string and a variable.

Whatever character can replace the underscore you want to use.

Print Formatting

This method has been replaced by str.format, but the method has not been deprecated yet. Keep this in mind if you plan on using this method, since it may be deprecated at some point.

In this method, you use a placeholder for the variable. Using a string, the placeholder is '%s'. The placeholders are:
  • %s - string
  • %d - decimal
  • %f - float
After the line, we add a section to specify the variable to be be placed into the placeholder. Let me give our last two lines of code for this example:

Code:
print ("Hello %s %s %s," %(prefix, firstname, lastname))
print ("We know you work for %s." %(workplace))

If we have a lot of variables, especially in a row like with the first line, this may get a little confusing. The code will not work if any of the variables are misspelled or placed in the wrong order.

The last section of the line is a percent sign (%) followed by parenthesis with the various variables separated with commas. Be sure the number of variables is used for the placeholders and the variables are in the correct order.

This may be a little easier to read as code, but let's look at more choices we have available.

str.print

The method of 'str.print' is the upgrade to the 'Print Formatting'. This method is similar to 'Print Formatting' as you'll see.

Instead of a placeholder to designate the variable type, we use curly braces ({}) to signify all placeholders. Let me just give the last two lines of the code using this method:

Code:
print ("Hello {} {} {}," .format(prefix, firstname, lastname))
print ("We know you work for {}." .format(workplace))

You can see that there is minor difference between the old and new methods. The 'str.print' method may be a little easier than 'Print Formatting'.

Another way to handle this is to use names as placeholders, then define the names to the variable that will replace it.

Code:
print ("Hello {Mr} {John} {Hancock}," .format(Mr=prefix, John=firstname, Hancock=lastname))
print ("We know you work for {Business}." .format(Business=workplace))

Let's look at this a little closer. In the example, I used a placeholder that actually uses an example for the variables. This makes the code very readable. At the end of each line, I set the placeholder equal to the variable name that will replace it. In this type of formatting, we do not need to specify the variables in the order they appear in the line. Since the placeholders are equal to the variable, we can place them in any order at the end of the line. For example, the first line could be:

Code:
print ("Hello {Mr} {John} {Hancock}," .format(Hancock=lastname , Mr=prefix, John=firstname))

Be sure that the placeholder names and the names at the end are the same. They are case sensitive. So, 'Mr' needs to be the placeholder and also used to set it equal to the variable 'prefix'. One cannot be 'Mr' and the other 'mr'.

f-string

This method may be a little easier to read as code, but it really is just a minor change from 'str.print'. In this method, we specify the variable with the placeholder. If the variable is descriptive, then it can be readable. Let's look at the last two lines:

This may be a little easier than 'str.print' by being required to assign a placeholder name to a variable. Here, we can do this all at once, as shown in the last two lines of the code using this method:

Code:
print (f"Hello {prefix} {firstname} {lastname},")
print (f"We know you work for {workplace}.")

Notice that there is an 'f' at the beginning of the print line after the opening parenthesis. The letter 'f' is required to make the formatting an 'f-string'.

Conclusion

You have seen the different methods to print unformatted and formatted lines.

Out of these, they all produce the same output and you may have one that seems better to you when coding. Try each of them and see if one may work better for you when coding.
 

Members online


Latest posts

Top