Home > Software engineering >  How do I split a list at full stops?
How do I split a list at full stops?

Time:08-03

I am trying to scrape eBay for graphics cards but I have a problem trying to separate values from a list. Is there a way I can get ['Pre-Owned','ZOTAC, 'NVIDIA GeForce RTX 3070 Ti', '8GB']

soup = BeautifulSoup(page, 'lxml')
art = soup.find_all('li', class_='s-item s-item__pl-on-bottom s-item--watch-at-corner')

for x in art:
    try:
        name = x.find('h3', class_='s-item__title').text
        price = x.find('div', class_='s-item__detail s-item__detail--primary').text
        shipping = x.find('span', class_='s-item__shipping s-item__logisticsCost').text
        con = x.find('div', class_='s-item__subtitle').text.split('.')```

>Output ```['Pre-Owned · ZOTAC · NVIDIA GeForce RTX 3070 Ti · 8 GB']```

 

CodePudding user response:

First, your output list contains strings, so you have to separate values in those strings. As in the python documentation described, you can do this by calling the str.split()-method.

In your example, ['Pre-Owned · ZOTAC · NVIDIA GeForce RTX 3070 Ti · 8 GB'] contains the string 'Pre-Owned · ZOTAC · NVIDIA GeForce RTX 3070 Ti · 8 GB' at index 0.

To get your output, you split that string by the separator used in it, in that case " · ". Your code would be:

['Pre-Owned · ZOTAC · NVIDIA GeForce RTX 3070 Ti · 8 GB'][0].split(" · ")

Alternatively, you can also iterate through the list; either by extending another list:

new_list = list()
for phrase in ['Pre-Owned · ZOTAC · NVIDIA GeForce RTX 3070 Ti · 8 GB']:
    new_list.extend(phrase.split(" · "))

or by changing the list in-place:

your_list = ['Pre-Owned · ZOTAC · NVIDIA GeForce RTX 3070 Ti · 8 GB']
for i in range(len(your_list)):
    your_list[i] = your_list[i].split(" · ")
  • Related