Question

I need to convert a list of ticker symbols: T GOOG KO PEP as examples in a a text file to a python list: ['T','GOOG','KO',PEP']. However, the current code I'm using keeps adding a space after each symbol yielding: ['T ','GOOG ','KO ',PEP '] instead. How can I get the tickers without spaces?

stocks = open('C:\Model\Stocks\official.txt', 'r').read()
print stocks.split('\n')
Was it helpful?

Solution

I suggest strip function, which maps the result:

>>> a = ["A ", "B ", "C "]
>>> a
['A ', 'B ', 'C ']
>>> a = map(lambda x: x.strip(), a)
>>> a
['A', 'B', 'C']

In your example:

a = stocks.split('\n')

OTHER TIPS

Here you go.

stocks = open('C:\Model\Stocks\official.txt', 'r').read()
lstStripped =  [x.strip() for x in stocks.split('\n')]
print lstStripped 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top