小白求教: Python format的用法

青松100 2020-08-28 02:49:39
以下代码是某爬虫视频教程的源码。小白想求教:16-21代码中,format的用法。

我百度了,然后也在B站看了几十分钟的format的用法,都提到要用{} -这对大括号来替换。

但是16行中的url中为什么没有{} , 21行却可以替换? --能不能告诉我,不需要用{}这对大括号的format的具体使用方法?或者说,我想知道这个知识点叫什么名字,或者我要用什么关键字才能搜到这个知识点?

引用
#16行: url = 'https://www.qiushibaike.com/pic/page/%d/?s=5184961'
#21行  new_url = format(url%pageNum)


如果我写成:这个是不是错了?
url = 'https://www.qiushibaike.com/pic/page/{}/?s=5184961'
new_url = format(pageNum)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import re
import os
#需求:爬取糗事百科中糗图板块下所有的糗图图片
if __name__ == "__main__":
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'

}
#创建一个文件夹,保存所有的图片
if not os.path.exists('./qiutuLibs'):
os.mkdir('./qiutuLibs')
#设置一个通用的url模板
url = 'https://www.qiushibaike.com/pic/page/%d/?s=5184961'
# pageNum = 2

for pageNum in range(1,3):
#对应页码的url
new_url = format(url%pageNum)


#使用通用爬虫对url对应的一整张页面进行爬取
page_text = requests.get(url=new_url,headers=headers).text

#使用聚焦爬虫将页面中所有的糗图进行解析/提取
ex = '<div class="thumb">.*?<img src="(.*?)" alt.*?</div>'
img_src_list = re.findall(ex,page_text,re.S)
# print(img_src_list)
for src in img_src_list:
#拼接出一个完整的图片url
src = 'https:'+src
#请求到了图片的二进制数据
img_data = requests.get(url=src,headers=headers).content
#生成图片名称
img_name = src.split('/')[-1]
#图片存储的路径
imgPath = './qiutuLibs/'+img_name
with open(imgPath,'wb') as fp:
fp.write(img_data)
print(img_name,'下载成功!!!')
...全文
720 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
青松100 2020-09-07
  • 打赏
  • 举报
回复
非常感谢大神再次耐心指导!
陈年椰子 2020-09-06
  • 打赏
  • 举报
回复 1
引用 6 楼 青松100 的回复:
[quote=引用 4 楼 陈年椰子 的回复:] 这个功能就是替换占位符,占位符可以是 %d %s 之类的形式, 也可以是 {} , 选择常用的方式, 尽量不要用不常用的方式, 不常用的方式,可能到下一个版本就取消了。 你举的例子已经够用啦。
万分感谢大神!我以为您不理我了,所以我看了两天没人答复,我就没有再上来了。没有想到您回复了。我原帖20,给您追加30分,共50分。一点评分不成敬意,只是表示由衷感谢您的付出。希望不要误解。 PS--另一个大神的回复也很详细,所以我也给TA追加50分。 [/quote] 你这种认真的精神非常可贵,开始学python , 建议先不用太多时间在细节, 先把整个框架过一遍,实际项目中,会碰到具体细节问题。 但如果已经有其他语言的经验,研究下细节,有助于深入了解python 精髓。
青松100 2020-09-06
  • 打赏
  • 举报
回复
也感谢楼中另一个大神的回复。
青松100 2020-09-06
  • 打赏
  • 举报
回复
@crifan 万分感谢大神这么详尽的回复,非常感动。拜谢!!!
青松100 2020-09-06
  • 打赏
  • 举报
回复
引用 4 楼 陈年椰子 的回复:
这个功能就是替换占位符,占位符可以是 %d %s 之类的形式, 也可以是 {} , 选择常用的方式, 尽量不要用不常用的方式, 不常用的方式,可能到下一个版本就取消了。 你举的例子已经够用啦。
万分感谢大神!我以为您不理我了,所以我看了两天没人答复,我就没有再上来了。没有想到您回复了。我原帖20,给您追加30分,共50分。一点评分不成敬意,只是表示由衷感谢您的付出。希望不要误解。 PS--另一个大神的回复也很详细,所以我也给TA追加50分。
crifan 2020-09-04
  • 打赏
  • 举报
回复 1
你的

url = 'https://www.qiushibaike.com/pic/page/%d/?s=5184961'
for pageNum in range(1,3):
new_url = format(url%pageNum)


可以改为:

url = 'https://www.qiushibaike.com/pic/page/{}/?s=5184961'
for pageNum in range(1,3):
new_url = url.format(pageNum)


或:

url = 'https://www.qiushibaike.com/pic/page/%d/?s=5184961'
for pageNum in range(1,3):
new_url = url % pageNum


关于

xxx.format("{}")


以及:

"%s" % xxx


的具体区别,专门写了,极其详尽的例子,全面演示如何使用:

# Function: Demo Python format value for:
# 小白求教: Python format的用法-CSDN论坛
# https://bbs.csdn.net/topics/397523895
# Author: Crifan Li
# Update: 20200904

################################################################################
# Demo Python format value
################################################################################

lastYearInt = 2019
curYearInt = 2020
piFloat = 3.1415
genderStr = "Male"
nameTuple = ("Crifan", "Li")

print('\n%s Method 1: "%%s" %% someValue %s' % ("="*20, "="*20))

########## single value ##########

# use %s also support integer value
print("Current year is: %s" % curYearInt) # Current year is: 2020
# use %d to format integer value
print("Current year is: %d" % curYearInt) # Current year is: 2020

print("PI=%s" % piFloat) # PI=3.1415
print("PI=%.2f" % piFloat) # PI=3.14

print("Your gender: %s" % genderStr) # Your gender: Male

# print("Your full name is: %s" % nameTuple) # Error: TypeError not all arguments converted during string formatting
print("Your full name is: %s" % (nameTuple, )) # Your full name is: ('Crifan', 'Li')

########## multiple value -> use tuple ##########

print("current year=%d and your full name=%s" % (curYearInt, nameTuple)) # current year=2020 and your full name=('Crifan', 'Li')


print("\n%s Method 2: someValue.format(""{}"") %s" % ("="*20, "="*20))
########## single value ##########

formattedYear_noIndex = "Current year is: {}".format(curYearInt)
print(formattedYear_noIndex) # Current year is: 2020
formattedYear_withIndex = "Current year is: {0}".format(curYearInt)
print(formattedYear_withIndex) # Current year is: 2020

print("PI={}".format(piFloat)) # PI=3.1415
# with format
print("PI={:.2f}".format(piFloat)) # PI=3.14

########## multiple value -> use index inside {} ##########

formattedTwoYear_withIndex = "Current year is: {0}, last year is: {1}".format(curYearInt, lastYearInt)
print(formattedTwoYear_withIndex) # Current year is: 2020, last year is: 2019
# with parameter name, can any order
print("last year is: {lastYear}, Current year is: {curYear}".format(curYear=curYearInt, lastYear=lastYearInt)) # last year is: 2019, Current year is: 2020


print("\n%s Method 3: format(someValue) %s" % ("="*20, "="*20))

print(format(curYearInt)) # 2020
print(format(piFloat)) # 3.1415
print(format(piFloat, ".2f")) # 3.14
print(format(genderStr)) # Male
print(format(nameTuple)) # ('Crifan', 'Li')


print("\n%s" % ("-"*80))

referUrl = """
7. 输入输出 — Python 3.8.5 文档
https://docs.python.org/zh-cn/3/tutorial/inputoutput.html
内置类型 — Python 3.8.5 文档
https://docs.python.org/zh-cn/3/library/stdtypes.html#str.format
6.1. string — Common string operations — Python 3.4.10 documentation
https://docs.python.org/3.4/library/string.html
2. Built-in Functions — Python 3.4.10 documentation
https://docs.python.org/3.4/library/functions.html#format
7.1. string — Common string operations — Python 2.7.18 documentation
https://docs.python.org/2/library/string.html#formatspec
"""
print("\n参考资料:%s" % referUrl)




陈年椰子 2020-09-04
  • 打赏
  • 举报
回复
这个功能就是替换占位符,占位符可以是 %d %s 之类的形式, 也可以是 {} , 选择常用的方式, 尽量不要用不常用的方式, 不常用的方式,可能到下一个版本就取消了。 你举的例子已经够用啦。
青松100 2020-09-02
  • 打赏
  • 举报
回复
引用 1 楼 陈年椰子 的回复:
这部分内容应该属于格式化输出 …………
大神,
引用
url = ' 'https://www.qiushibaike.com/pic/page/%d/?s=5184961' for pageNum in range(1,3): #对应页码的url new_url = format(url%pageNum)
大神,我明白%d 是十进制。 forumat(url%pageNum)这里的url前面不用加逗号, 就是要被替换的字符串; 而后面是要被替换的内容? 您给我的链接我都看了,好象没有老式的用法。万一没看清,您能不能把具体的用法或关键字复制过来,这样我可以再找一下。 PS---不好意思,这几天有事,所以回帖晚了。如果您帮助我这个问题,我再追加30分,表示诚意,行吗?
兰振lanzhen 2020-08-29
  • 打赏
  • 举报
回复
字符串格式化三种写法:
陈年椰子 2020-08-28
  • 打赏
  • 举报
回复
这部分内容应该属于格式化输出 参考下这个 https://www.cnblogs.com/limengjie0104/archive/2018/05/31/9118416.html 对于你提的问题,这样应该可以

url = 'https://www.qiushibaike.com/pic/page/{}/?s=5184961'
new_url = url.format(pageNum)
个人看法是尽量只用一种写法, 建议用 {} 的方式。

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧