In Python we concatenate or interpolate strings all the time. There are many methods, but the latest in Python 3.6 is the f string
. Let's see how we can use this feature to manipulate strings much easier than before.
Let's say we have some details from a video game character, and we want to create a string representation. Let's look at a few ways to do this.
name = "Balthazar"
hp = 50
str = 100
mp = 20
formatted1 = name + " $ hp: " + str(hp) + " - str: " + str(str) + " - mp:" + str(mp)
print(formatted1)
formatted2 = '%s $ hp: %s - str: %s - mp: %s' % (nam, hp, str, mp)
print(formated2)
formatted3 = f'{name} $ hp: {hp} - str: {str} - mp: {mp}'
print(formatted3)
The last example is the new f-string
. Here, we can add a f
before our string and then use {}
to add variables into our string. This is fairly simple to do string interpolation in Python.