Python talks about the format in the string

When we need to insert variables in a string, we can use the string format()method. format()method can insert one or more parameters into the specified string, thus generating a new string.

format()The basic syntax of a method is as follows:

string.format(arg1, arg2, ...)

Among them, stringis the string to be formatted, arg1, arg2etc. are the variables to be inserted, which can be Python data types such as numbers, strings, lists, tuples, and dictionaries.

format()The method supports a variety of formatting methods, including positional parameters, keyword parameters, format strings, etc. Here are some common usage examples:

  1. positional parameters

Positional parameters refer to inserting variables into the string in order. For example:

name = "Tom"
age = 18
print("My name is {}, and I'm {} years old.".format(name, age))

The output is:

My name is Tom, and I'm 18 years old.
  1. keyword arguments

Keyword arguments refer to the method of specifying the insertion position by variable name. For example:

name = "Tom"
age = 18
print("My name is {n}, and I'm {a} years old.".format(n=name, a=age))

The output is:

My name is Tom, and I'm 18 years old.
  1. format string

Formatting a string refers to using specific formatting symbols in a string to insert variables into specified positions. For example:

name = "Tom"
age = 18
print(f"My name is {
      
      name}, and I'm {
      
      age} years old.")

The output is:

My name is Tom, and I'm 18 years old.

The method of is used here f-string, curly brackets are used {}to indicate the position of inserting variables, and variable names are used in curly brackets to specify the variables to be inserted.

In addition, format()the method also supports more formatting methods, such as specifying the data type and alignment of variables. For specific usage, please refer to the official Python documentation.

Guess you like

Origin blog.csdn.net/gaoxiangfei/article/details/131320427