python study notes - check the type and format string

One,

String (str) is a data type,

Including the values: integer (int type), float (float type), the complex, are data types

There is a type Integer Boolean (bool)

Type checking:

= A ' Hello ' 
B = type (A)       # #### type () is a function that is specifically designed to check what data type of the return value of this function, we typically use a variable to accept the return value, such as B 
Print (B) 
run results:
 < class  ' STR ' >

 

This way is to print a type, you can check what data type.

 two,

Format string: the format string output

It may be spliced ​​between the strings, adding is performed:

= A ' ABC ' + ' haha ' + ' ha ' 
Print (A) 
operation result: 
abchaha ha

 

It may be spliced ​​between the strings, but the string (str) and can not be spliced ​​between the other data types are added to avoid an error.

 

We want to see this format in the console: a = hahaha. .

The first format string ways: one way is spliced

= A ' hahaha ' 
Print ( ' A = ' + A)     # This is not a common, less frequently used 
operation results: 
A = hahaha

 

In the second method:

= A ' hahaha ' 
Print ( ' A = ' , A)     # separated by commas at both ends of the string, but there is a space between the two strings runs Results 
Run Results: 
A = hahaha

 

The third way:

When creating a string, the string can be specified in the placeholder

= A ' hahaha% s ' % ' ha ' 
Print (A)        
Run Results: 
hahaha ha            
 # accounted string in the character string position by% s,% + followed by a string of splicing in this manner to realize a , we achieve the desired format 
a = ' hahaha ' 
Print ( ' a = S% ' % a) 
run results: 
a = hahaha

 

In addition there is a placeholder string, other data types are:

% S indicates the character string placeholder

% F represents float placeholder

% D represents an integer of placeholders

a = 'hahaha%3s'%'ab'
#%3s 表示最少占三个字符字符串,填充的字符串不足三位,以空格代替,空格在第一位
print(a)
运行结果:
hahaha ab
a = 'hahaha%3.5'%'abfasd'
#%3.5s 表示字符串长度限制在3-5个之间,不足3个以空格代替,大于五个则省略后边

 

 

a = 'hahaha%.2f'%1.234567
print(a)
hahaha1.23
#%.2f占位符保留两位小数

a = 'hahaha%d'%123455.352
print(a)
hahaha123455
#%d 占位符保留整数

 

第四种方式:

格式化字符串,可以通过在字符串前添加一个f来创建一个格式化字符串

在字符串中可加入直接嵌入变量

a = 'hello'
b = 'hahaha'
c = f'哈哈{a}{b}'
print(c)
哈哈hellohahaha

print(f'a={a}{b}')

 

这就是按照我想排列的格式进行输出的四种方式

关于四种方式的练习:

创建一个变量保存自己的名字,用四种方式打印出   欢迎:xxx光临

name = 小猪佩奇

一、拼接

print('欢迎:'+name+'光临')
欢迎:小猪佩奇光临

 

二、多个参数

print('欢迎:',name,'光临') 
欢迎:小猪佩奇光临

 

三、占位符

print('欢迎:%s光临'%name) 
欢迎:小猪佩奇光临

 

四、格式化字符串

print(f'欢迎:{name}光临') 
欢迎:小猪佩奇光临

 

 

Guess you like

Origin www.cnblogs.com/takein/p/12294346.html