'Add quote to every item in a Python List
I have the following Python list from BeautifulSoup (for example):
[Basketball, Ipad Pro, Macbook Pro, Racket]
I need to add quote to every item in the list, as shown below:
['Basketball', 'Ipad Pro', 'Macbook Pro', 'Racket']
I have tried several methods, but not getting the right result.
The actual script:
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'})])
For the products, I got the list as shown above.
Solution 1:[1]
Your list [Basketball, Ipad Pro, Macbook Pro, Racket]
is not valid list
in python. You may try to Add quote to every item in a Python List this way:
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'"]
Solution 2:[2]
Consider as string: test_list = "Basketball, Ipad Pro, Macbook Pro, Racket" print(test_list.split(','))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Md. Rezwanul Haque |
Solution 2 | thangaraj1980 |