Monday 16 September 2019

Python 3, using Split (and Tuples)


Split [generic definition and capabilities]




The simplest way to use split is by defining a line of something, then split the words up, implicitly, using a space as delimiter:


>>> line="just some typing as an illustration"
>>> line.split()
['just', 'some', 'typing', 'as', 'an', 'illustration']

using str.split(" ") would have the same result; the sentence is turned into a list.


line="just some sentence to illustrate something"
words_list=line.split()
print(words_list)      

Or, for example print(word-list[2][1])  to print from word 2  (typing) the letter at position 1 (y) (remember couting starts at 0)





So I have created a csv file, using xls, see below. The good things about csv file is that it is built up by continuous rows, delimited by a comma. It is therefore no more than logical to use the split command to separate the data again.



summing up the company name, number of shares and price.




# File containing lines of the form "name,shares,price"
filename = "shares.csv"
portfolio = []
for line in open(filename):
    fields = line.split(",") # Split each line into a list using "," as the delimiter.
    name = fields[0] # Extract and convert individual fields
    shares = int(fields[1])
    price = float(fields[2])
    stock = (name,shares,price) # Create a tuple (name, shares, price)
    portfolio.append(stock) # Append to list of records



Call the tuple for instance:

>>>portfolio[0]
('Philips', 100, 100.5)



No comments:

Post a Comment