Python爬虫日记- format格式以及f表达式

Format 使用方法

  1. 无指定的format
print('{} {}'.format('hello','world'))  
#hello放在第一个空格{}, world放在第二个空格{}
#[hello world]
  1. 有指定的format
print('{0} {1}'.format('hello','world')) 
#0代表format后面的第一个字符,1代表第二个字符
# [hello world]
print('{0} {1} {0}'.format('hello','world'))
#记住,format括号里面的字符中,hello代表0,world代表1 
#所以print出来的是 
# [hello world hello]
  1. 用关键词来指定format里面的字符
print('{a} {tom} {a}'.format(tom = 'hello', a = 'world'))  
#output为
# 【world hello world】

f表达式 – f可以解释任意的数据类型

name = '张三'
age = 18
print(f"名字: {name} 年龄: {age: .2f}")
#output
#【名字: 张三 年龄:  18.00】
rf_scores= model()
print(f'Linear Regression average RMSE: {rf_scores.mean():.4f}')
# :.4f代表着解析的数字round4位
#output为
#【Linear Regression average RMSE: 0.6102】

猜你喜欢

转载自blog.csdn.net/Jiana_Feng/article/details/109407198