[Python] f strings should be used for embedding strings

Source

This article was compiled by reading item 4: "** Embedding in f string without using C-style format string and str.format " in " Effective Python 2nd Edition **". Thing.

Python string embedding

There are three main methods for embedding character strings in Python.

--How to use% --How to use str.format () --How to use f string

I used it without much consciousness, but I would like to take this opportunity to think about which one is appropriate.

How to use%

This is a method familiar to those who are doing Java or C language. Write as follows.

name = 'Cheese beef bowl Taro'
age = 21 
print('my name is%s.%I'm d years old.' % (name, age))

output

My name is Cheese Gyudon Taro. I'm 21 years old.

Yup. Looks good. But actually, there are some problems with this method. Let's look at the following example.

name = 'Cheese beef bowl Taro'
age = 21 
weight = 55.1525 
 
print('my name is%s.%I'm d years old. Weight is about%It is dkg. From now on%Nice to meet you.' % (name, age, int(weight), name))

output

My name is Cheese Gyudon Taro. I'm 21 years old. It weighs about 55 kg. Thank you for your continued support of Cheese Gyudon Taro.

The above code has the following four problems.

-** Problem 1: If you make a mistake in the order of the types, an error will occur **

For example, if you reverse the first name and ʻage` in the above code, you will get the following error:

Traceback (most recent call last):
  File "cheese.py", line 8, in <module>
    print('my name is%s.%I'm d years old. Weight is about%It is dkg. From now on%Nice to meet you.' % (age, name, int(weight), name))
TypeError: %d format: a number is required, not str

The first type is an integer and the second is a character string type, so you can't reverse it. You must always be careful about the type and order.

-** Problem 2: The longer it gets, the harder it is to read **

In the above case, weight is converted to an integer, but the more complicated the formula to be assigned, the lower the readability. "Which variable corresponds to which?" You need to look carefully.

-** Problem 3: Need to write multiple times when using the same value ** In the above example, the same variable called name is used twice, but it is necessary to write it twice in the tuple on the right side.

-** Problem 4: Redundant using a dictionary **

Problems 1 and 3 can be solved by using dictionaries instead of tuples. You can write as follows.

name = 'Cheese beef bowl Taro'
age = 21 
weight = 55.1525 
 
print('my name is%(name)s.%(age)I'm d years old. Weight is about%(weight)It is dkg. From now on%(name)Nice to meet you.' % {'age':age, 'name':name, 'weight':int(weight)})

The output is the same. If you write it like this, you only have to write the name that appears twice, and you don't have to worry about the order of the variables. However, using a dictionary made it even more verbose and messy.

How to use the built-in format or str.format

Next, let's see how to use str.format ().

name = 'Cheese beef bowl Taro'
age = 21 
print('my name is{}is.{}歳is.'.format(name, age))

Write like this. You can also change the order of the variables by setting the index as shown below.

print('my name is{1}is.{0}歳is.'.format(age, name))

Apply to the previous example.

name = 'Cheese beef bowl Taro'
age = 21 
weight = 55.1525 
 
print('my name is{0}is.{1}歳is.体重はだいたい{2}kgis.これからも{0}Nice to meet you.'.format(age, name, int(weight)))

It seems that problems 1 and 3 above can be solved by using index. However, although it is cleaner than the method using a dictionary with %, it is still redundant.

How to use f string

Finally, consider the method using the f character string. Write like this.

name = 'Cheese beef bowl Taro'
age = 21 
weight = 55.1525 
 
print(f'my name is{name}is.{age}歳is.')

Apply to the previous example

name = 'Cheese beef bowl Taro'
age = 21 
weight = 55.1525 

print(f'my name is{name}is.{age}歳is.体重はだいたい{int(weight)}kgis.これからも{name}Nice to meet you.')

You can see that it is much cleaner than the method using % or str.format (). Readability is high because variables are embedded directly instead of being specified by tuples, dictionaries, or format () on the right side. It doesn't matter which code you use, but the more complex it is, the better it is to use the f string.

Summary

--Summary of how to embed strings in Python --The method using the f string is the most readable, so it looks good. --By the way, note that str.format () can only be used with Python2.6 and the f string must be Python3.6 or higher.

Recommended Posts

[Python] f strings should be used for embedding strings
33 strings that should not be used as variable names in python
++ and-cannot be used for increment / decrement in python
[Python] Which should be used, return or return None
Search for strings in Python
What is Python? What is it used for?
I created a template for a Python project that can be used universally
Python strings become f strings by default (maybe)
Mathematical optimization that can be used for free work with Python + PuLP
Summary of frequently used Python arrays (for myself)
Astro: Python modules / functions often used for analysis
2016-10-30 else for Python3> for:
python [for myself]
[Python] Building an environment for competitive programming with Atom (input () can be used!) [Mac]
Authentication information used by Boto3 (AWS SDK for Python)
Python note: When the pip command cannot be used
Japanese can be used with Python in Docker environment
Python knowledge notes that can be used with AtCoder
[Memorandum] Japanese keys cannot be used in python string.Template.substitute
list comprehension because operator.methodcaller cannot be used in python 2.5
Operators ++,-cannot be used in python (difference from php)
Can be used in competition pros! Python standard library
Python3> slice copy / slice notation> used in for statements, etc.
[Redash] Standard library cannot be used in python function
Can be used with AtCoder! A collection of techniques for drawing short code in Python!