What are good reasons to use string formatting?

According to this lesson, the .format() method is used instead of string concatenations for better code legibility, however, I find the format method to be less legible than string concatenations personally.

I’m wondering, which method does everyone else find more legible? And for the more experienced Python coders out there - what is the de facto standard that is more regularly used by professionals?

Concatenation does not provide any means for formatting, which is the purpose of all three methods in Python:

  1. % formatting
  2. str.format
  3. f-strings

With formatting we can restrict output length. pad the output, round numbers, and so on with little manual manipulation.

See the pyformat link posted above for more details.

14 Likes

Ok now those are good reasons to use .format(), thanks for the clarification!

1 Like

@zackary.pugh - Hello!

I definitely find the str.format() method to be more legible! While I am still a beginner, I can think of a few times where I found that concatenating looked less seemly than str.format() and felt a bit arduous.

For example, I can remember times in which I wanted to concatenate strings with integers, and I had to use str() in order to change the integer into a string during the concatenation process and it just felt a little uncomfortable.

#using concatenation
amount = 30
random_string = "I want to receive $" + str(amount) + " for my birthday."
print(random_string)
#prints:
#I want to receive $30 for my birthday.

#using str.format()
amount = 30
random_string = "I want to receive ${} for my birthday.".format(amount)
print(random_string)
#prints:
#I want to receive $30 for my birthday.

I also feel like it can be more difficult to remember to add necessary spaces when concatenating strings. In the example above, I initially forgot to put a space before the “for” in “for my birthday” in the concatenation example, but it felt smooth and easy to add spaces in the str.format() example because the {} felt like a pleasant placeholder.

However, I also believe that whether concatenation is more legible than the str.format() method depends on the context. I suppose I can just think of quite a few contexts in which the str.format() method feels much nicer than concatenation!

27 Likes

Hello Okaraman, it’s wonderful to get someone else’s detailed thoughts, thank you!

I tend to agree, a lot of it seems to be context and personal preference - for that reason I plan on probably using the Python community-standard to make it easier for others to read my code!

4 Likes

If you like str.format(), you may also like f-string. You can also use additional formatting with either method.

#using str.format() with additional float formatting
amount = 30
random_string = "I want to receive ${:.2f} for my birthday.".format(amount)
print(random_string)
#prints:
#I want to receive $30.00 for my birthday.

#using f-string with additional float formatting
amount = 30
random_string = f"I want to receive ${amount:.2f} for my birthday."
print(random_string)
#prints:
#I want to receive $30.00 for my birthday.

Happy coding!

15 Likes

Hi @midlindner!

Thank you for sharing this with me! I’m actually very glad you mentioned this float formatting in particular because I’m currently working on a project that is adding up a number of dollar amounts in a list, saving this number to a variable, and printing that variable. The number that is printed has 13 decimal places, so I tried looking up how to have the number rounded to 2 decimal places and then I saw this response from you! How convenient! :slight_smile:

I recently heard the term f-string, so I am glad you showed me an example of this as well! It appears to be a step up from str.format() as you can include the variable in the string and all you need outside of the string is a singular f - that seems quite legible and pleasant-looking!

Out of curiosity, do you know if there are any downsides/drawbacks of using f-strings as opposed to str.format()? Or is this another instance of the best method to use depends on the context of the situation in which it is being used?

4 Likes

I don’t know of any drawbacks/advantages regarding f-string vs. str.format(). I believe it’s simply a matter of preference. When including the float or other formatting, some may consider one version easier to read than the other.

1 Like

What you probably mean is that you’re counting cents, not dollars. Use int.
Floats are for when you wish to approximate something, what you’re doing should probably be exact.

the format method can be called at a later time, f-strings are immediately interpolated

3 Likes

Hadn’t considered that, but makes sense. Thanks!

1 Like

Quick questions!
I use the f-string method for formatting, means f"{variable}", is there any difference between using this and using .format() or % formatting
Thanks in advance!

It’s generally advised to avoid the % interpolation syntax if possible. For .format and f-strings the posts above mention immediate interpolation as a difference and the following covers some of the more obvious syntax / implementation differences- Python 3's f-Strings: An Improved String Formatting Syntax (Guide) – Real Python

There’s some very mild differences in internal syntax- https://www.python.org/dev/peps/pep-0498/#differences-between-f-string-and-str-format-expressions
Python 3.8 also introduced the nice f-string f"{var = }" syntax option- https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging

There may be some other bits but you might need to search around to find them.

Thank you Okaraman, I was confused at the beginning but now i get it because of your explanation !

Hi
What would be the difference if I use triple quote marks or scape characters? Which one is better?

def poem_title_card(title,poet):
return “”“The poem “{}” is written by {}.”“”.format(title,poet)

def poem_title_card2(title, poet):
poem_desc = “The poem "{}" is written by {}.”.format(title, poet)
return poem_desc

In Python, triple-quoted strings and escape characters serve different purposes, and the choice between them often depends on the specific requirements of your code.

  1. Triple-Quoted Strings:
def poem_title_card(title, poet):
    return f"""The poem "{title}" is written by {poet}."""
  • Advantages:
    • Easier to write multiline strings without using explicit line continuation characters (\).
    • Convenient for embedding both single and double quotes within the string without the need for escaping.
    • Can be used for docstrings in functions and classes.
  1. Escape Characters:
def poem_title_card2(title, poet):
    poem_desc = 'The poem "{}" is written by {}.'.format(title, poet)
    return poem_desc

Advantages:

  • More concise for short strings.
  • Can be used in situations where you want to control the exact placement of line breaks using \n for readability.

Can you explain by any example, how to restrict output length, and other advantages of using .format(), rather than concat?

The advantages will be readily apparent once we get familiar with all the available directives (may require some searching for a table). As for length, it may require slicing. Been ages since I did any experimenting, so will have to leave this in your court.

Python f-strings - The Ultimate Usage Guide-SaralGyaan

2 Likes

Thanks, will read it, new to python actually

2 Likes