Python Reviewing Notes

来源:互联网 发布:网络lp地址怎么设置 编辑:程序博客网 时间:2024/06/05 02:37

# how to get help with python built-in functions

1. dir

# here a code of pythona = 'strings'dir(a)


Then all attrs or functions of a as a string will be presented.


2. help

# help funtion, to get the detailed explaination of a certain functiona = 'strings'help(a.rsplit)  1 #Help on built-in function rsplit:  2 #  3 #rsplit(...)  4 #    S.rsplit([sep [,maxsplit]]) -> list of strings  5 #  6 #    Return a list of the words in the string S, using sep as the  7 #    delimiter string, starting at the end of the string and working  8 #    to the front.  If maxsplit is given, at most maxsplit splits are  9 #    done. If sep is not specified or is None, any whitespace string 10 #    is a separator.


3. .__doc__

a.rsplit.__doc__     #this way can also find the detailed info of rsplit function


# get map

b = ['ee', 'aa']c = { i:b[i] for i in range(len(b)) }# c --> {0: 'ee', 1:'aa'}


# search map with default keys.

# D = {1:'aa'; 2:'bb'}value = D.get('x', 0) # if 'x' not in D, then return 0 instead# 0# or in this wayvalue = D['x'] if 'x' in D else 0# 0

NOTE:

x if y else z  # if y is true, then return x, else return z

# decimal, precise type of number

from decimal import DecimalDecimal('0.1') ** 4# get Decimal('0.0001') , a precise number over float type

# fraction,  such as 1/7, 1/9

# fractions, such as 1/7from fractions import Fractionx = Fraction(1, 7)y = Fraction(1, 7) ** 3# y --> Fraction(1, 343)

# set

>>> a = set('helloworld')>>> aset(['e', 'd', 'h', 'l', 'o', 'r', 'w'])>>> b = set(['e', 'd', 'a'])>>> a|bset(['a', 'r', 'e', 'd', 'w', 'h', 'l', 'o'])>>> a&bset(['e', 'd'])

# concatenation of strings

>>> title = 'w' 'ee'>>> title'wee'>>> title = 'w' + 'ee'>>> title'wee'>>> title = ('w'... 'eee')>>> title'weee'

# escape string

>>> c = 'C:\py\codes\t\ex'>>> c'C:\\py\\codes\t\\ex'#\p --> \\p, \t --> \t#if no certain characters after '\', then '\' --> '\\'

# turn off escaping string function

>>> c = 'C:\py\codes\t\ex'>>> print cC:\py\codes\ex>>> c = r'C:\py\codes\t\ex'>>> print cC:\py\codes\t\ex

#ASCII

>>> print '\x61\x00\x61'  #'\x61' --> chr(97) --> 'a'aa>>> print '\x61\x08\x61'   # '\x08' --> backspacea

# convert into int from strings

>>> int('0xff', 16)255

#format strings with dict

>>> temp = '%(name)s is a guy, %(t)10.3f' % {'name': 'jk', 't': 1.7}>>> temp'jk is a guy,      1.700'











0 0