0

I'm running into a bit of difficulty trying to extend a list.

The problem section of code is:

l = []

tickers = soup.find_all('td', {'aria-label': 'Symbol'})[1:].text

l.extend(tickers)

When I print tickers it comes out as expected with one ticker per line. However, when I try to add them to a list, it shows as one letter per line. Even when I save it to csv it's one letter per line.

Any suggestions on how to fix this?

quamrana
  • 37,849
  • 12
  • 53
  • 71
Hansel313
  • 15
  • 3
  • To add a single element to a list, use `.append()` rather than `.extend()`. – jasonharper Feb 18 '22 at 20:52
  • 1
    There is an answer to this [question](https://stackoverflow.com/questions/22042948/split-string-using-a-newline-delimiter-with-python) which suggests `splitlines()` – quamrana Feb 18 '22 at 20:54
  • `tickers` is a string. When you use a string as a sequence, it's a sequence of characters, not lines. – Barmar Feb 18 '22 at 20:58
  • "When I print tickers it comes out as expected with one ticker per line." Yes, because it has newline characters in it - but it is still **one string**. "However, when I try to add them to a list, it shows as one letter per line." Yes, because `.extend` means to put **each element** of `tickers` into the list, and the elements of a string are the individual Unicode code points (letters, newline characters etc.). – Karl Knechtel Feb 18 '22 at 21:03

1 Answers1

1

You have to separate the items into a list before using .extend() by using .splitlines():

l = []

tickers = soup.find_all('td', {'aria-label': 'Symbol'})[1:].text

l.extend(tickers.splitlines())
Eli Harold
  • 2,280
  • 1
  • 3
  • 22