Friday, May 24, 2013

python google class.

python strings:
-------------------------------------------------------------------------
1. 
built in string class named str, single quote or double quote both OK. use """ for multiple line string. 

2. 
string are immutable. 

3. 
zero-based indexing for accessing string with [] 
ex: 
str = 'hello'   str[1] is e

4. 
don't use "len" as variable name!

5. 
+ to cat two strings. 

6.
a raw string : 
raw = r'this\t\n and that'
print raw

7. 
string slicing:

s = 'hello' 
print s[1:4]
print s[1:]
print s[:]
print s[1:100]

note the last one. 

8. 
string methods modifies the original string. 

print list.append(4) # this doesn't work 


python sorting 
---------------------------------------------------------------------------------
1. 
sorted(a)  doesn't change the original list.

2. 
sorted() method is recommended over the old sort() method, because the former can take as input any iterable collection .

3. 
sorted() string compare their ascii number lexicographically. 
capital letters are smaller

4. 
sort by length:

strs = ['ccc', 'aaa', 'd', 'bb']
print sorted(strs, key=len)

5. 
custom key function. 

strs = ['xc', 'zb', 'yd', 'wa']
def myFn(s):
    return s[-1]
print sorted(strs, key = myFn)



Tuples
-----------------------------------------------------------------
1.
fixed size grouping of elements. 

2. 
immutable and don't change size

3. 
function that returns fixed number multiple values may just return a tuple.

4.
tuple = (1,2,'hi')
print len(tuple)
print tuple[2]
tuple[2] = 'bye' # not going to work!!!!!!
tuple = (1,2, 'bye') # this works

5.
create a single element tuple, the lone element has to be followed by a comma:
tuple = ('hi',)
to distinguish a tuple from a parenthesized string. 

----------------------------------
done 






No comments:

Post a Comment