Search code examples
pythonstringstring-formattingstring-concatenation

Is it more Pythonic to use String Formatting over String Concatenation in Python 3?


So I'm programming a text game in Python 3.4 that requires the use of the print() function very often to display variables to the user.

The two ways I've always done this is with string formatting and string concatenation:

print('{} has {} health left.'.format(player, health))

And,

print(player + ' has ' + str(health) + ' health left.')

So which is better? They're both equally as readable and quick to type, and perform exactly the same. Which one is more Pythonic and why?

Question asked as I couldn't find an answer for this on Stack Overflow that wasn't concerned with Java.


Solution

  • Depends upon how long your string is and how many variables. For your use case I believe string.format is better as it has a better performance and looks cleaner to read.

    Sometimes for longer strings + looks cleaner because the position of the variables are preserved where they should be in the string and you don't have to move your eyes around to map the position of {} to the corresponding variable.

    If you can manage to upgrade to Python 3.6 you can use the newer more intuitive string formatting syntax like below and have best of both worlds:

    player = 'Arbiter'
    health = 100
    print(f'{player} has {health} health left.')
    

    If you have a very large string, I recommend to use a template engine like Jinja2 (http://jinja.pocoo.org/docs/dev/) or something along the line.

    Ref: https://www.python.org/dev/peps/pep-0498/