字符串拼接3种方法

时间:2021-02-24 05:22:52
datelist[] = ['20180107', '20180114', '20180121', '20180128', '20180204']

  1. %

for i in range(len(datelist)):
base_url = 'https://index.baidu.com/Interface/Newwordgraph?word=%E9%A9%AC%E4%BA%91&datelist=%s'
url = base_url % datelist[i]

报错信息:
Traceback (most recent call last):
File "D:/Programe/indexbaidu/getdata.py", line 27, in <module>
url2 = base_url % datelist[i]
TypeError: must be real number, not str

2. format
base_url = 'https://index.baidu.com/Interface/Newwordgraph?word=%E9%A9%AC%E4%BA%91&datelist={kwarg}'
url = base_url.format(kwarg=datelist[i])

pass

3.f-string
url = f'https://index.baidu.com/Interface/Newwordgraph?word=%E9%A9%AC%E4%BA%91&datelist={datelist[i]}'
pass