Hackernoon logoPython Fundamentals (5) — Placeholders in Python strings by@sltrask

Python Fundamentals (5) — Placeholders in Python strings

Mr Trask Hacker Noon profile picture

Mr Trask

Let’s dive right in with some Python strings here:

We can see that, as previously, we are printing (“Hello world”) in the first line. We are also assigning a value to the name variable, but this time we are doing this via an input function.

The input function displays a string of text, and it awaits an input from the user. In this case, the text is “What is your name?” and it clearly expects the user to type a response here. Once the user has entered a response, this data is immediately assigned (put into) to the variable called name.

However, note that we have four ways in which was can display (print) this data. The first wayon line 4 is a simple print (name) command — nothing crazy there.

Line 5 features the + operator we saw previously. This creates string concatenation — it joins strings together, and it requires you to judiciously insert a space into your string in order to display properly. This is why my executed code displays as ‘HelloSteve’ with no space.

Line 6 use a comma rather than a +. The comma is essentially a way of separating items in a string, and was used extensively in Python 2. It is perfectly respectable, and it handily inserts a space automatically when separating items, as you can see above.

Line 7 uses something known as string interpolation — and it is much more flexible than the other two because it allows you to position your variables much more easily than using + or ,. Essentially you are creating something known as a placeholder — the placeholder here is the {0} — and you then use the .format function to put the contents of the (name) variable into the placeholder. Since the name variable contains the word Steve, then Python looks at the string “Hello {0}”, it sees there is a magical item called a placeholder there, and it understands that it needs to look further ahead for a .format command. When it finds the .format command, it places the contents of the name variable into that little {0} place.

Is this using a sledgehammer to crack a nut? Well in this case, yes, but that is only because this is a very simple case. Take this one with three variables. See how much easier, more elegant and more, well, Pythonic, it is to create three variables, assign them with values from input statements, and then display them using the {0} {1} and {2} placeholders?

Python tracks the order of the placeholders, and the order of the variables in the .format command, and inserts them very cleanly into the code. The smart money, on any code of complexity, is to use placeholders. This principle extends to arrays, or lists, in Python, and we will tackle that in the future. For now, placeholders should be your best friend.


Join Hacker Noon

Create your free account to unlock your custom reading experience.