将引号添加到Python列表中的每个项目

时间:2017-07-12 13:57:13

标签: python regex beautifulsoup

我有来自BeautifulSoup的以下Python列表(例如):

[Basketball, Ipad Pro, Macbook Pro, Racket]

我需要为列表中的每个项添加引号,如下所示:

['Basketball', 'Ipad Pro', 'Macbook Pro', 'Racket']

我尝试了几种方法,但没有得到正确的结果。

实际脚本:

from bs4 import BeautifulSoup

products =[]
prices = []
for page in range(1,9):
    url = 'https://www.lelong.com.my/catalog/all/list?TheKeyword=ipad+pro&D='+str(page)
    r = requests.get(url)
    prices.extend([price.find('b') for price in soup.find_all('span',{'class':'price pull-right'})])
    products.extend([title.find('b') for title in soup.find_all('div',{'class':'summary'})])

对于产品,我得到了如上所示的列表。

1 个答案:

答案 0 :(得分:0)

您的列表[Basketball, Ipad Pro, Macbook Pro, Racket]在python中无效list。您可以尝试以这种方式为Python列表中的每个项添加引号:

arr = ['Basketball', 'Ipad Pro', 'Macbook Pro', 'Racket']
A = []
for x in arr:
    A.append("'" + x + "'")
print(A)
# output : 
# A = ["'Basketball'", "'Ipad Pro'", "'Macbook Pro'", "'Racket'"]