Understand! Format method of Python string format

Time:2020-11-21

Format is a method embedded in a string to format a string. Braces with braces{}To indicate the replaced string to some extent%The purpose is the same. But in some ways it’s more convenient

1. Basic usage

1. Match the values in parentheses in order of {}

s = "{} is a {}".format('Tom', 'Boy')
print(s) # Tom is a Boy

s1 = "{} is a {}".format('Tom')
#Throw an exception, replacement index 1 out of range for positive args tuple
print(s1)

2. Match parameters by index

It should be noted here that the index is calculated from 0.

s = "{0} is a {1}".format('Tom', 'Boy')
print(s) # Tom is a Boy

s1 = "{1} is a {2}".format('Tom', 'Lily', 'Girl')
print(s1) # Lily is a Girl

The order of indexes in a string can be disordered without affecting the match.

s = "{1} is a {0}".format('Boy', 'Tom', )
print(s) # Tom is a Boy

3. Match parameters by parameter name

s = "{name} is a {sex}".format(name='Tom', sex='Boy')
print(s) # Tom is a Boy

Similarly, if the parameters have been determined, you can directly use {} to format the reference.

name = 'Tom'
sex = 'Girl'
#Starting with F indicates that Python expressions in braces are supported in strings
s = f"{name} is a {sex}"
print(s) # Tom is a Boy

4. Mix and match

You can mix and match indexes and parameter names.

s = "My name is {}, i am {age} year old, She name is {}".format('Liming', 'Lily', age=10)
print(s) # My name is Liming, i am 10 year old, She name is Lily

It is important to note that named parameters must be written last. Responsible for compiling error!

s = "My name is {}, i am {age} year old, She name is {}".format('Liming', age=10, 'Lily')
print(s)  # SyntaxError: positional argument follows keyword argument

In addition, you cannot mix index with Default Formatting.

s = "{} is a {0}".format('Boy', 'Tom', )
print(s)


s1 = "{} is a {1}".format('Boy', 'Tom', )
print(s1)

The above two methods are abnormal.

# ValueError: cannot switch from automatic field numbering to manual field specification

2. Advanced usage

1. Supports partial reference to parameters

The part of the parameter can be valued by index. As follows: s [0] = W.

s = "The word is {s}, {s[0]} is initials".format(s='world')
# The word is world, w is initials
print(s)

2. Digital processing

There’s nothing to say about ordinary direct matching numbers, just like string matching in the basic part.

s = 'π is {}'.format(3.1415926)
print(s) # π is 3.1415926

How to use format to keep two decimal places? Need to use:.2fWhen formatting with% we use%:.2f

s = 'π is {:.2f}'.format(3.1415926)
print(s) # π is 3.14

s1 = 'π is %.2f'% 3.1415926
print(s1) # π is 3.14

At the same time, this method can also be used for string interception, but the number can not be followed by F.

s = "{:.1}".format('Hello')
print(s) # H 

Add a thousand to a number

s = "{:,}".format(1000000)
print(s) # 1,000,000

Convert numbers to binary

s = "{:b}".format(8)
print(s) # 1000

Convert a number to octal

s = "{:o}".format(8)
print(s) # 10

Convert a number to hexadecimal

s = "{:X}".format(12)
print(s) # C

The summary is as follows

  • b: Binary mode of output integer;
  • c: Output the Unicode characters corresponding to integers;
  • d: Decimal mode of output integer;
  • o: Output integer octal mode;
  • x: Output integer in lower case hexadecimal mode;
  • 10: Hexadecimal integer output in uppercase;

3. Format processing

adopt: + numberSpecifies the length of the converted String, and the insufficient part is supplemented with spaces

s = "{:2}b".format('a')
Print (s) # a B (a space is added after a)
#If the specified length is less than the length of the parameter, match according to the original parameter
s1 = "{:2}World".format('Hello')
print(s1) # HelloWorld

4. Filling of characters

Can be passed through: symbol ^ numberFill in the string. Where number is the total length of the filled string.

s = "{:*^10}".format('Hello')
print(s) # **Hello***

s = "{:-^20}".format('123456')
print(s) # -------123456-------

If the number is less than the length of the string, no padding is performed.

s = "{:*^3}".format('Hello')
print(s) # Hello

5. Splitting of list and tuple

When format is formatted, you can use*perhaps**Split the list and tuple.

foods = ['fish', 'beef', 'fruit']
s = 'i like eat {} and {} and {}'.format(*foods)
# i like eat fish and beef and fruit
print(s)
foods = ['fish', 'beef', 'fruit']
s = 'i like eat {2} and {0} and {1}'.format(*foods)
# i like eat fruit and fish and beef
print(s)
dict_temp = {'name': 'Lily', 'age': 18} 
#The dictionary needs to be split with * *
s = 'My name is {name}, i am {age} years old'.format(**dict_temp)
print(s) # My name is Lily, i am 18 years old

The most complete collection of Python data in history (long-term update). The children next door are crying for food — Click to get it

Understand! Format method of Python string format

Recommended Today

Regular expression sharing for checking primes

This regular expression is shown as follows: Regular expressions for checking prime numbers or not To use this positive regular expression, you need to convert the natural number into multiple 1 strings. For example, 2 should be written as “11”, 3 should be written as “111”, 17 should be written as “11111111111”. This kind of […]