Python data-types

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

Some Python Data types


In short strings are a bunch of letters or numbers inside quotation marsk (either single or double).

Learn more in

s="I am a string" #assign string to variable s

# some String methods and opertations:
print '.upper():', s.upper()
print '.replace():', s.replace('string', 'bunch of letters or numbers inside quotations')

print '.startswith()', s.startswith('I') 
print  '.endswith()',s.endswith('strings') 
print 'integer to string:', str(2)
print 'adding strings:', s + " " + "in python" + " " + str(2)
print '.split():',s.split(' ') # split string to list at empty space ' '


Are collections of python data values, each element is identified by an index corresponding to its position in the list.

Lists are writen with square brackets and contain different data-types (integer,floats,strings,lists,etc) inside one list.

Learn more in

# Lists
l = [10, 100, 'a string']
print l
print 'element at index 1:', l[1] 
print 'index of element "a string":', l.index("a string")
print 'lenght of string:', len(l)

l.append('another string')
l.append([1,2,3]) # appending a list to the list
print 'expanded list:',l

print 'reduced list:',l

# list creation
print 'a list from 0 to 19:', range(20)


Dictionaries or objects a like lists. They store data of different type. The major difference bieng: * lists store data in sequences, whose values are accessed using its index position * dictionaries storage data in key:value pairs, whose values are accessed using the key

Like lists it allows many data-types: numbers (integer or float), strings, lists, dictionaries (a dictionary containing a dictionary), Null (An empty value)

More on Python dictionaries

# create a dictionary
piratelibs = {'Memory_or_the_World':'Marcel Mars',
    'aaaarg': 'Sea Dockray',
     'Monoskop':'Dusan Barok',
     'Sci-hub': 'Alexandra Elbakyan'
scihub = piratelibs['Sci-hub'] # access one of its keys
print scihub

# add a new key do the dictionary

# loop trhough all the dictionary keys
for k in piratelibs.keys():
    print 'Key:', k
    val = piratelibs[k]
    print 'Value:', val