Basic Python Strings

Python3 has representation of String using unicode.Unicode is by default in python.

Python has dynamic typing e.g. print(3+"mangesh") will not work need to convert 3 to str(3)


In [1]:
print(3+"mangesh")


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-f83eb4d6f450> in <module>()
----> 1 print(3+"mangesh")

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [2]:
print(str(3)+"mangesh")


3mangesh

In [3]:
record={"name":"mangeesh","price":34,"country":"Brazil"}


Using format


In [4]:
print_statement="{} is my name,{} is the price,{} is the country"

In [5]:
print_statement.format(record["name"],record["price"],record["country"])


Out[5]:
'mangeesh is my name,34 is the price,Brazil is the country'

CSV_Reading


In [21]:
import csv

#precision 2

with open("mpg.csv") as csvfile:
        mpg=list(csv.DictReader(csvfile))
        print(len(mpg))
        print(mpg[0].keys())
        print(mpg[0])


398
dict_keys(['origin', 'displacement', 'mpg', 'cylinders', 'acceleration', 'name', 'horsepower', 'weight', 'model_year'])
{'origin': '1', 'displacement': '307', 'mpg': '18', 'cylinders': '8', 'acceleration': '12', 'name': 'chevrolet chevelle malibu', 'horsepower': '130', 'weight': '3504', 'model_year': '70'}

In [26]:
sum([float(k["displacement"]) for k in mpg] )/len(mpg)


Out[26]:
193.42587939698493

Sum over cylinders


In [32]:
cylinders=set([k["cylinders"] for k in mpg])


Out[32]:
{'3', '4', '5', '6', '8'}

In [37]:
avgMpgPerCylinderDict={}

for c in cylinders:    
    value=0
    number=0
    for k in mpg:
        if k["cylinders"]==c:
            value+=float(k["mpg"])
            number+=1
    avgCylinderDict[c]=value/number        

avgCylinderDict


Out[37]:
{'3': 20.55,
 '4': 29.28676470588236,
 '5': 27.366666666666664,
 '6': 19.985714285714284,
 '8': 14.963106796116508}

In [41]:
modelyear=set([d["model_year"] for d in mpg])
modelyear


Out[41]:
{'70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82'}

In [53]:
avgMPGperModelYear=[]

for y in modelyear:
    value=0
    number=0
    for k in mpg:
        if k["model_year"]==y:
            value+=float(k["mpg"])
            number+=1
    avgMPGperModelYear.append((y,value/number))
avgMPGperModelYear.sort(key=lambda x:x[1])
avgMPGperModelYear


Out[53]:
[('73', 17.1),
 ('70', 17.689655172413794),
 ('72', 18.714285714285715),
 ('75', 20.266666666666666),
 ('71', 21.25),
 ('76', 21.573529411764707),
 ('74', 22.703703703703702),
 ('77', 23.375),
 ('78', 24.061111111111114),
 ('79', 25.09310344827585),
 ('81', 30.33448275862069),
 ('82', 31.70967741935484),
 ('80', 33.696551724137926)]