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?
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!
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!
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.
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!
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?
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.
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
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
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.
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.
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.
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.