SoFunction
Updated on 2024-11-13

Examples of python string formatting

I. Old-style string formatting

% operator

Refer to the following examples:

>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'

When there are multiple variables to be inserted into the string:

>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello, Eric. You are 74.'

When the number of variables to be replaced increases further, use the % Operator formatted strings can cause code readability to become poor:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

()

() Yes, it is.% approach, which uses the syntax of common function calls and can be used by defining the object's own__format__() method controls the specific behavior of string formatting.

Basic Usage:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'

() as opposed to% Operators have more flexibility. For example, you can associate variables that are substituted into a string with a numeric index:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {1}. You are {0}.".format(age, name)
'Hello, Eric. You are 74.'

To improve code readability, the{} You can also use parameter names with specific meanings:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {name}. You are {age}".format(name=name, age=age)
'Hello, Eric. You are 74'

against dictionary-structured data:

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
'Hello, Eric. You are 74.'

Or a more concise way:

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(**person)
'Hello, Eric. You are 74.'

The problem is that when there are a lot of variables to replace, the() approach can still result in code that becomes too lengthy:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, {first_name} {last_name}. You are {age}. \
  You are a {profession}. You were a member of {affiliation}."\
  .format(first_name=first_name, last_name=last_name, age=age, \
  profession=profession, affiliation=affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

II. f-string

basic usage

>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'

Embedded Expressions

>>> f"{2 * 37}"
'74'

>>> def to_lowercase(input):
...   return ()
  
>>> name = "Eric Idle"
>>> f"{to_lowercase(name)} is funny"
'eric idle is funny'

>>> f"{()} is funny"
'eric idle is funny'

f-string It is also possible to embed an object instance directly in an object, as long as it internally implements the__str__ or__repr__ Methods:

class Comedian:
  def __init__(self, first_name, last_name, age):
    self.first_name = first_name
    self.last_name = last_name
     = age

  def __str__(self):
    return f"{self.first_name} {self.last_name} is {}"


new_comedian = Comedian("Eric", "Idle", 74)
print(f"{new_comedian}")
# Eric Idle is 74

Multi-line f-string

>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
...   f"Hi {name}. "
...   f"You are a {profession}. "
...   f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

bibliography

Python 3's f-Strings: An Improved String Formatting Syntax (Guide)

Above is the details of python string formatting example, more information about python string formatting please pay attention to my other related articles!