Old image of a waving child in a bathtub

Hello, world: the inevitable print() article

As you’d expect, both PHP and Python support printing to standard output. Let’s start our Python for PHP Programmers journey, as is traditional, by printing Hello, World. We can make it a little more interesting by using a variable for part of the output. As we’ll see, while there’s little confusing in the shift from PHP to Python, there are some wrinkles to consider – a few that might catch you out.

PHP Code Example:

Let’s get on and print using PHP.

$name = "World";
print "Hello, {$name}\n";

We assign the string "World" to the $name variable. Then we add the variable to a string and print the lot.

Python Code Example:

Here’s the equivalent code in Python.

name="World"
print(f"Hello, {name}")

We’ll cover most of the divergences in the discussion below – but note that we did not need to add a newline character. Notice, also, that leading f ahead of the string we print. What work do you think it’s doing?

Note See Declaring and assigning to variables for more on variables.

Output

The output should be exactly the same across languages.

Hello, World

Discussion

As simple as these examples are, there are several things to note here right away.

print in PHP is a language construct and not a function, so it does not require parentheses (though you can use them if you want to – just as you can surround any expression in parentheses). Python’s print(), on the other hand, is a function and the parentheses are therefore mandatory.

Note print was a statement in Python 2

In our PHP example, we had to provide a newline character \n within the string. In contrast, Python’s print() function automatically adds a new line onto the end of any string you pass it. Usually, that’s handy. You can suppress the new line (or replace it with something else) using the end keyword argument.

name="bob"
print(f"Hello, {name}", end="")

Note We will cover keyword arguments when we look at creating and calling functions. In essence, though, print() accepts any number of comma separated positional arguments which it will attempt to output as strings, followed by any combination of the named keyword arguments end, sep and flush which influence the behaviour of the print() function. We will cover sep and end in this article.

Notice that leading f prefixing the string we passed to print()? That’s an instance of a feature named f-strings (or formatted string literals). f-strings were added in Python 3.6. They allow you to evaluate expressions within a string using braces just as you can within double-quoted PHP strings. Unless you’re planning to support older versions of Python, you’ll likely want to use f-strings by default for variable interpolation.

Variable interpolation in PHP only works within double quoted strings. The same is not true for f-strings. Like its double-quoted cousin, this will happily greet bob:

print(f'Hello, {name}')

# OUTPUT:
# Hello, bob

F-strings will work with all kinds of expression, not just variables. Here, I call a function from within an f-string.

def sayHello():
    return "wotcher"
print(f"A salutation: {sayHello()}")

# OUTPUT:
# A salutation: wotcher

Note see the manual for some of the more arcane formatting tricks you can play with f-strings.

There are other ways to include expressions in your Python string. Let’s take a quick abbreviated tour:

You can use concatenation. While PHP uses . for concatentation, Python concatenates with ‘+’.

# concatenation
print("Name ("+name+")")

# OUTPUT:
# Name: (bob)

print() accepts multiple arguments, which is another way of combining string literals and expressions:


# multiple arguments
print("Name (", name, ")");

# OUTPUT:
# Name: ( bob )

Note, though, that this adds spaces between the parentheses and the name variable. By default, print() inserts a space between arguments. You can suppress (or alter) that behaviour with another keyword argument: sep.

# multiple arguments, no separator
print("Name (", name, ")", sep="")

# OUTPUT:
# Name: (bob)

Finally, because everything in Python is an object, you can call the format() method directly on any string you pass to print().

# format() method
firstname="bob"
secondname="smith"

print("Name ({} {})".format(firstname, secondname))

# OUTPUT:
# Name (bob smith)

Any arguments you add to format() are passed along to the corresponding {} placeholder in the string. You can even mix up the order if you want by using numerically labelled placeholders:

print("Name ({1}, {0})".format(firstname, secondname))

# OUTPUT:
# Name (smith, bob)

Note There’s a lot more to format(). See the manual entry for the gory details.

That’s it for print() basics. We’ll be returning to the topic, though, when we look at files and other kinds of output.

See also

Further Reading:

Stay up to date with the Python for PHP Programmers project


Yes! Please sign me up to this newsletter


Photo by Social History Archive on Unsplash