String formatting details of f'', str.format() and str%() in Python (1)------placeholders and functions str(), repr(), ascii(), object references and description

Contents
1. Format placeholders and functions str(), repr(), ascii()
(1) Format placeholders (format converters)
(2) Functions str(), repr(), ascii()
2. f References to objects in '', str.format() and str%() format expressions
3. Add characters described in f'', str.format() and str%() format expressions

Detailed explanation of string formatting of f'', str.format() and str%() in Python

       

       Sometimes we need to process or describe the object when printing () output, so that the output meets our requirements, or better present the results for our understanding (that is, increase the readability of the output results), at this time, we can Make some related settings on the print object of print, so that the print output of print is output in a certain format to meet our print output requirements. Usually we use the strings of f'', str.format() and str%() Formatting (formatted string, formatted output) to achieve the printing effect of print. Of course, f'', str.format() and str%() can also be used in other scenarios. f'' string formatting is often referred to as f-string string formatting.

1. Format placeholders and functions str(), repr(), ascii()

       For the specific use of string formatting of f'', str.format() and str%(), some placeholders will be involved. Therefore, here is the python format placeholder. These three string formatting can also be abbreviated as f formatting, format formatting, and % operator formatting.

(1) Format placeholder ( format conversion character)

        Format placeholder, the name originated from the C language, indicating that there is input or output at this position (for example: used in functions such as scanf(), printf()), and the placeholder indicates that data in a certain format is generated at this position. In python, it can also be understood as a format conversion character, and it also means to perform related conversions for objects. The previous name is used here. Table 1-1 below shows several commonly used format placeholders (format conversion characters).

Table 1-1 Commonly used format placeholders (format conversion characters)

s

String (displayed by str()), ns can also be used, n represents the output width, that is, the number of output occupants

r

String (display using repr()), nr can also be used, n is the same as above

a

String (ascii() display), na, n same as above can also be used

c

A single character, also available nc, n same as above

b

Binary integer, can only be used in f'', str.format(), nb can also be used, n is the same as above

d

Decimal integer, also available nd, n same as above

o

Octal integer, also available no, n same as above

x

Hexadecimal integer, you can use X or nx, n is the same as above

f

Decimal floating-point numbers, that is, decimals

.mf

m is precision, which means retaining m decimal places

n.mf

n indicates the output width, that is, the number of output positions, m indicates that m decimal places are reserved, and .m can be defaulted

e

Scientific notation, exponential form, the base is e (equivalent to 10), and E can also be used

.me

m means to keep m decimal places

n.me

n indicates the output width, that is, the number of output positions, m indicates that m decimal places are reserved, and .m can be defaulted

g

If the exponent is less than -4 or greater than 5, use e, otherwise, use d or f by default, or G

.mg

Reserve m significant digits (numbers), if the exponent is less than -4 or greater than m-1, then use e, otherwise, use d

n.mg

n is the output width, that is, the number of output places, m is the same as above, and the value format is the same as above, .m can be default

%

% character

      The format placeholders listed above will add corresponding symbols in str%(), f'', and str.format(), for example: the placeholders in str%() will add the symbol %, and in f'' and str.format() format expressions are used in other symbols. str%() does not support conversion to binary %b, and will prompt unsupported format character 'b'.

(2) Functions str(), repr(), ascii()

       The format placeholder s in Table 1-1 uses the result of the function str() to obtain a human-readable text string. The format placeholder r uses the result of the function repr() to convert the object into a form that is more suitable for the interpreter to read, and its return value is also a string type. From the perspective of use, the repr() function adds to the expression The effect of a pair of quotation marks .

       str(), repr() respectively call the __str__(), __repr__() methods, the object class contains these two methods, and all python classes inherit the object class, so all python classes inherit __str__(), __repr__() method. The function print will call the __str__() method by default when printing, so the print output of the function print is actually automatically converted to a string format.

sr1 = 'Hello,Python\n'
#print打印默认调用了__str__()方法,显示出的文本字符串,适合人阅读,
#相当于执行了转义符\n。
print(sr1)
#repr(sr1)实际获得的值为"'Hello,Python\n'",
#但经过print打印调用了__str__()方法,显示为'Hello,Python\n'。
print(repr(sr1))
#上面相当于下面。
#格式占位符表示该位置会产生一个什么格式的数据。
#str%()中格式占位符都会增加符号%,下面%r表示该位置产生repr()函数返回的字符串格式的数据,
#实际也是依次引用右边小括号的实参进行格式化。
#下面print打印也调用了__str__()方法。
print('%r'%(sr1))

#数字的字符串格式。
sr2=str(123)
print(type(sr2),sr2)
#对于字符串,增加引号。
print(type(repr(sr2)),repr(sr2))
#对于非字符串的整型,增加引号。
print(type(repr(123)),repr(123))

print('%s'%(123))#s即为str()
print('%r'%(123))#r即为repr()

operation result:

        The function repr() is equivalent to adding a pair of quotation marks, and the eval() function can be used to restore the result of repr() to the original data. For the usage of the parsing function eval, please refer to Chapter 9 of this blog.

sr1 = 'Hello,Python'
#根据eval的执行特点,下面是可行的,但不能直接用eval(sr1)。
#eval执行了"'Hello,Python'",得到结果'Hello,Python',sr1引用了它。
sr1=eval(repr(sr1))
#print打印默认调用了__str__()方法,显示出的文本字符串,适合人阅读。
print(sr1)

operation result:

       

       We can rewrite the __str__() or __repr__() method in the class, and the class will automatically execute the rewritten __str__() or __repr__() method when it is instantiated. This automatic execution is similar to __init__(), when When both are overridden, __str__() is executed by default.

class Group:
    def __init__(self,name,age):
        self.name = name
        self.age = age

#返回类对象地址,打印出类对象地址。
print(Group('Bor',23))


class Member:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __repr__(self):
        return ('名字是:%s,年龄是:%d')%(self.name,self.age)

#重写了__repr__方法,类实例化时自动执行__repr__方法。
#打印自动执行__repr__方法的返回值。
print(Member('Bor',23))


class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __repr__(self):
        return ('名字是:%s,年龄是:%d')%(self.name,self.age)

    def __str__(self):
        return ('name is %s,age is %d')%(self.name,self.age)

#重写了__repr__、__str__方法,类实例化时默认自动执行__str__方法。
#打印自动执行__str__方法的返回值。
print(Student('Bor',23))

operation result:

       The format placeholder a in Table 1-1 uses the result of the function ascii() , and the return is the character decoded according to the ASCII encoding standard. If it cannot be encoded in ASCII, it will use \x, \u (or \U) Escape, and then add quotation marks, similar to the repr() function, except that the encoding standard is different when decoding.

sr1='abc\n'
#对字符串增加引号,是ASCII解码的字符串。
print(type(ascii(sr1)),ascii(sr1))
print('%a'%(sr1))

sr2='你好'
#对汉字字符串增加引号,不能用ASCII解码,则会用\x、\u进行转义。
print(type(ascii(sr2)),ascii(sr2))
print('%a'%(sr2))

n1=129
#对整型增加引号,是ASCII解码的数字字符串。
print(type(ascii(n1)),ascii(n1))
print('%a'%(n1))

print('\n')
print(type(repr(sr2)),repr(sr2))
print(type(sr2),sr2)

print(type(repr(n1)),repr(n1))
print(type(str(n1)),str(n1))
print('%s'%(n1))

operation result:

       The result of ascii() is decoded or escaped using the ASCII encoding standard, and quotes are added. Type and ASCII encoding standards can participate in the following related content.

       Next, we will describe the specific use of string formatting of f'', str.format() and str%(). f'' string formatting is often referred to as f-string string formatting.

2. References to objects in f'' , str.format() and str%() format expressions

        The basic forms of f'', str.format(), and str%() references to objects are:

        f'{name}', this expression does not support the reference to the parameter object, where name represents the name (identity of the object), which is a reference to the object, and the name here cannot be defaulted;

       '{name}'. format(), where the parentheses of format() are parameters, which can be positional parameters or keyword parameters, that is, str.format(*args, **kwargs) is supported, and name is also used here The reference of the object of the actual parameter, but the name here is the ordinal number corresponding to the positional actual parameter in format() (the ordinal number starts from 0) or the keyword of the keyword parameter. When format() is a keyword actual parameter, name cannot Default, if the quotes indicate the overall operation of only one positional actual parameter or the overall operation of each positional actual parameter in order, then the name of the ordinal number can be defaulted, if the local operation is performed on the positional actual parameter, it means the ordinal number The name cannot be defaulted;

       '%(name)'% (), this expression is not suitable for referencing keyword parameters, where the right parentheses () are parameters, if the parameter is a dictionary, you can use name to refer to the object in the dictionary, otherwise, name default. In addition, if there is only one parameter in the parentheses () on the right, the parentheses can be defaulted.

       The name reference of f'' has nothing to do with the parameters, but the name references of str.format() and str%() are related to the parameters, and str.format() and str%() refer to the objects in the dictionary quite specially, which is different from There are differences in the reference of keyword parameters. str.format() and str%() refer to objects in the dictionary. Only certain data types can be used as reference names, and this name is in the form of identifiers ( style), but the name does not necessarily conform to the standard (standard) for the formation of identifiers. Please refer to the following examples for details. The following examples are references to objects by various format expressions.

sr1,sr2='ab','cd'
te1 = {'kr': 'ij', 10: 31, '12': 89,'15y':76}
lt1=[1,2,3]

print("f'':")
#f''是通过名称引用对象,对字典的键值的引用是通过键名引用,这也是字典的引用方式。
print(f'{sr1},{sr2},{te1},{te1["kr"]},{te1[10]},{te1["12"]},{te1["15y"]}')

print('\nstr.format():')
#对于位置实参,str.format()若是按顺序引用小括号()中的位置实参,{}中可缺省序数。
#不能出现有的有序数,有的缺省序数这种形式。对于关键字实参,关键字不能缺省。
print('{},{z},{},{}'.format(sr1,sr2,te1,z=3))
#但引用对象的局部的元素时,应该使用序数。
print('{0},{1[0]},{2}'.format(sr1,sr2,te1))
#序数代表了对应的位置实参。
print('{1},{2},{0}'.format(sr1,sr2,te1))

#下面是借助键名对位置参数字典中的对象(键值)进行引用,
#但不支持键名为数字字符串的,其它都支持,并且引用方式类似标识符引用,
#而不是直接使用键名(字典的引用方式)。
#下面键名10、'15y'类似标识符进行引用,但不支持数字字符串键名'12',
#注意,对参数te1里面再次进行引用,这时不再是参数引用。
print('{0[kr]},{0[10]},{0[15y]}'.format(te1))

#下面是关键字参数进行引用,因为函数的关键字参数对应为变量,关键字参数实际也是变量,
#而变量名(变量名也是标识符)的首个符号不能是数字,因此,下面只能使用关键字kr。
#下面是对实参**te1进行解包,对关键字参数进行引用,具体可以参加前面讲到的动态参数。
print('{kr}'.format(**te1))

#下面是对位置实参的引用。
print('{2},{0},{1}'.format(*lt1))

#str.format()可以通过关键字引用关键字实参,也可以引用其局部元素。
print('{y},{y[1]}'.format(y=[7,8,9]))

print('\nstr%():')
#str%()不适合引用关键字参数。
#格式占位符表示该位置会产生一个什么格式的数据。
#str%()中格式占位符都会增加符号%,下面%s表示该位置产生字符串格式的数据,
#实际也是依次引用右边小括号的实参进行格式化。
print('%s,%s'%(sr1,sr2))
#借助键名对位置参数字典中的对象进行引用,
#但不支持数字的键名,其它都支持,并且引用方式类似标识符引用,
#而不是直接使用键名(字典的引用方式)。
#下面键名'kr'、'12'、'15y'类似标识符进行引用,但不支持数字键名10。
print('%(kr)s,%(12)s,%(15y)s'%(te1))

print('\n通过路径引用对象:')
class AA:
    a1=1
    a2=2

print(f'{AA.a1},{AA.a2}')
print(f'{AA().a1},{AA().a2}')
#下面只能变成关键字参数才能引用。
print('{t.a1},{t.a2}'.format(t=AA))
print('{t.a1},{t.a2}'.format(t=AA()))

operation result:

      The use of f'', str.format(), and str%() are complementary to a certain extent, and each has its own characteristics. Moreover, f'' and str.format() do not need to use placeholders. In the above code, f'' and str.format() do not use placeholders, but str%() requires placeholders. The name of f'' must exist and cannot be defaulted.

      In python , references to objects generally come in three basic forms. One is to refer to by serial number, for example: sr1[2], 2 is the index. The other is to use the key name to refer to, which is the reference of the key name nature, such as: dictionary dt1['bd'], 'bd' is the key name. Another is to use identifiers to refer, for example: variable num=856, num is a variable. From the above example, we can see that the name references of str.format() and str%() have certain particularities. There is a reference to an approximate identifier, but it does not conform to the specification of the identifier.

Three, f'' , str.format() and str%() format expressions to increase the characters described

sr1='abc'
k1=len(sr1)

#f''
print(f'字符串{sr1}的长度是{k1}')
#或用str.format()
print('字符串{0}的长度是{1}'.format(sr1,k1))
#或用str%()
print('字符串%s的长度是%d'%(sr1,k1))

operation result:

       Three formatting expressions of f'', str.format() and str%() are listed above. The above printout is a printout in a certain format. This kind of formatted output makes the printed result more readable. If you use print(sr1,k1), it is obviously less readable. It is not intuitive to simply look at the result, but The descriptive formatted printing above, the result of the printout let us know at a glance.

Detailed string formatting explanation of f'', str.format() and str%() in Python (2):

https://blog.csdn.net/thefg/article/details/130941724

Finally, you are welcome to like, bookmark, and follow!

Guess you like

Origin blog.csdn.net/thefg/article/details/130940550