Did you know? Programmers convert coffee to code.

If you like my articles, sponsor me a coffee.

At the other end of the link I post some results of my other hobbies, like playing bass. It is worth checking it out ;)

Python format strings

Long time no real blog entry but now I have something juicy for you: format strings — introduced in Python 3.6.

Because my content template behaves like a pile of crap with Python interactive interpreter prompts in code blocks, assume that the code examples below are written into Python’s interactive interpreter and having >>> instead of >. And excuse any other formatting issues with > and <

String formatting pre-3.6

Before I dive into the topic of the new string formatting solution, let’s recap which other options exist in Python for string formatting.

Concatenation

Bad thing, bad habit but it works.

> name = 'Gabor'
> age = 33
> 'The user ' + name + ' is ' + str(age) + ' years old.'
'The user Gabor is 33 years old.'

As you can see, it works nicely, as long as you deal with strings. If you need to add a numeric value into the concatenation, you have to convert it to string explicitly — which is odd and makes things complicated.

%

> name = 'Gabor'
> age = 33
> 'The user %s is %d years old.' % (name, age)
'The user Gabor is 33 years old.'

Alternatively, you can “hack” your way around using %s instead of %d if you deal with integer values — or using %s for any arbitrary numerical value (floats not just integers):

> 'The user %s is %s years old.' % (name, age)
'The user Gabor is 33 years old.'

str.format

And the one I like the most because it makes readable what you want to achieve: formatting a string to contain specified values:

> name = 'Gabor'
> age = 33
> 'The user {} is {} years old.'.format(name, age)
'The user Gabor is 33 years old.'

If you want to go a step further in readability, you can add position markers / placeholder numbers to your format string:

> 'The user {0} is {1} years old.'.format(name, age)
'The user Gabor is 33 years old.'

This solution makes you decrease understandability if you switch the parameters:

> 'The user {1} is {0} years old.'.format(age, name)
'The user Gabor is 33 years old.'

And the ultimate solution is to use placeholder names in your string:

> 'The user {name} is {age} years old.'.format(name=name, age=age)
'The user Gabor is 33 years old.'

The new format strings

Now we have another way of formatting strings. To do this, we only need to mark the string as a format string and use the variables as placeholders:

> name = 'Gabor'
> age = 33
> f'The user {name} is {age} years old.'
'The user Gabor is 33 years old.'
> print(f'The user {name} is {age} years old.')
The user Gabor is 33 years old.

Continuing the code above, I alter the age:

> age += 1
> f'The user {name} is {age} years old.'
'The user Gabor is 34 years old.'

As you can see, the result is updated.

How does a format string work? Simply: put an f before the string and put the variables you want to output into curly braces into the string. That’s string interpolation — what you can find in some other programming languages like Elixir.

Caveat

You cannot use this string as a template. For example, we start over with a new console and we want to define the string above as the value of a variable:

> info_template = f'The user {name} is {age} years old.'
Traceback (most recent call last):
File '<stdin>', line 1, in <module>
NameError: name 'name' is not defined

As you can see, this is a no-go because the string is evaluated as soon as you create it — and the required variables are not present. Even if we use the example above we can encounter strange behavior if we forget about this property of format strings:

> name = 'Gabor'
> age = 33
> info_template = f'The user {name} is {age} years old.'
> info_template
'The user Gabor is 33 years old.'
> age += 1
> info_template
'The user Gabor is 33 years old.'

Conclusion

The new format strings are groovy — but if you need a template for your code, stick with the old str.format function call.

In other cases — feel free to use this solution because this makes your code readable in my opinion.

 

 

Share the knowledge!
←Previous post Next post→
GHajba
 

Senior developer, consultant, author, mentor, apprentice. I love to share my knowledge and insights what I achieve through my daily work which is not trivial -- at least not for me.

Click Here to Leave a Comment Below 0 comments
>
%d bloggers like this: