python入门

part1——python编码

在初次编程的过程中,我们常常会遇到代码中汉字变乱码的情况,首先,就让我们的编码从不乱码开始吧!

1、在python编码过程中Unicode和utf-8及gbk之间的关系:

在Windows中解释器模式的是gbk编码,即使你在代码头部定义了utf-8,系统还是会按照自己想要的方式呈现。所以就需要一个先解码,在编码的过程。

2、python2.7版本中utf-8解码Unicode再编码gbk的过程:

代码说明:
#!/usr/bin/env python
#_*_coding:utf-8_*_
#__author__="tina"

temp="不乱码显示中文"
temp_unicode=temp.decode("utf-8")
temp_gbk = temp_unicode.encode('gbk')
print(temp_gbk)
#print("显示中文".decode('utf-8').encode('gbk'))
#decode解码,encode编码

3、python3中utf-8将自动转换成gbk,就不用上面的代码啦~\(≧▽≦)/~啦啦啦~

part2——python中的运算符

1、算数运算符

代码说明:

 #!/usr/bin/env python
 #-*-coding:utf-8-*-
 #__author__ = "tina"
 a = 22
 b = 11
 c = 0
 
 c = a + b
 print "eg1:Value of c is ", c
 
 c = a - b
 print "eg2:Value of c is ", c
 
 c = a * b
 print "eg3:Value of c is ", c
 
 c = a / b
 print "eg4: Value of c is ", c
 
 c = a % b
 print "eg5: Value of c is ", c
 
 a = 3
 b = 3
 c = a**b 
 print "eg6: Value of c is ", c
 
 a = 10
 b = 5
 c = a//b 
 print "eg7:Value of c is ", c
 
 当执行上面的程序,它会产生以下结果:
 
 C:\Python27\python.exe E:/python/day2test.py
 eg1:Value of c is  33
 eg2:Value of c is  11
 eg3:Value of c is  242
 eg4: Value of c is  2
 eg5: Value of c is  0
 eg6: Value of c is  27
 eg7:Value of c is  2

 

2、比较运算符

代码说明:

#!/usr/bin/env python
 #-*-coding:utf-8-*-
 #__author__ = "tina"
 
 a = 22
 b = 11
 c = 0
 
 if ( a == b ):
   print "eg1: a is equal to b"
 else:
   print "eg1: a is not equal to b"
 
 if ( a != b ):
   print "eg2: a is not equal to b"
 else:
   print "eg2: a is equal to b"
 
 if ( a <> b ):
   print "eg3:a is not equal to b"
 else:
   print "eg3: a is equal to b"
 
 if ( a < b ):
   print "eg4: a is less than b" 
 else:
   print "eg4:a is not less than b"
 
 if ( a > b ):
   print "eg5:a is greater than b"
 else:
   print "eg5:a is not greater than b"
 
 a = 6
 b = 66
 if ( a <= b ):
   print "eg6: a is either less than or equal to b"
 else:
   print "eg6: a is neither less than nor equal to b"
 
 if ( b >= a ):
   print "eg7: b is either greater than or equal to b"
 else:
   print "eg7: b is neither greater than nor equal to b"
 
 执行以上代码,显示结果如下:
 
 C:\Python27\python.exe E:/python/day2test.py
 eg1: a is not equal to b
 eg2: a is not equal to b
 eg3:a is not equal to b
 eg4:a is not less than b
 eg5:a is greater than b
 eg6: a is either less than or equal to b
 eg7: b is either greater than or equal to b

 

3、赋值运算符

代码说明:

#!/usr/bin/env python
#-*-coding:utf-8-*-
#__author__="tina"

a = 22
b = 11
c = 0

c = a + b
print "eg1: Value of c is ", c

c += a
print "eg2: Value of c is ", c 

c *= a
print "eg3: Value of c is ", c 

c /= a 
print "eg4: Value of c is ", c 

c = 2
c %= a
print "eg5: Value of c is ", c

c **= a
print "eg6: Value of c is ", c

c //= a
print "eg7: Value of c is ", c

执行以上代码,显示结果如下:

C:\Python27\python.exe E:/python/day2test.py
eg1: Value of c is  33
eg2: Value of c is  55
eg3: Value of c is  1210
eg4: Value of c is  55
eg5: Value of c is  2
eg6: Value of c is  4194304
eg7: Value of c is  190650

 

4、逻辑运算符

代码说明:

 #!/usr/bin/env python
 #-*-coding:utf-8-*-
 #__author__ = "tina"
 a = 22
 b = 11
 c = 0
 
 if ( a and b ):
   print "eg1:a and b are true"
 else:
   print "eg1:Either a is not true or b is not true"
 
 if ( a or b ):
   print "eg2:Either a is true or b is true or both are true"
 else:
   print "eg2:Neither a is true nor b is true"
 
 
 a = 0
 if ( a and b ):
   print "eg3:a and b are true"
 else:
   print "eg3:Either a is not true or b is not true"
 
 if ( a or b ):
   print "eg4:Either a is true or b is true or both are true"
 else:
   print "eg4:Neither a is true nor b is true"
 
 if not( a and b ):
   print "eg5:Either a is not true or b is not true"
 else:
   print "eg5:a and b are true"
 
 
 执行以上代码,显示结果如下:
 
 C:\Python27\python.exe E:/python/day2test.py
 eg1:a and b are true
 eg2:Either a is true or b is true or both are true
 eg3:Either a is not true or b is not true
 eg4:Either a is true or b is true or both are true
 eg5:Either a is not true or b is not true

 

5、成员运算符

代码说明:

#!/usr/bin/env python
#-*-coding:utf-8-*-
#__author__ = "tina"
a = 2
b = 11
li = [1,2,3,4,5,6]

if(a in li):
    print "eg1:a is available in the given list"
else:
    print "eg1:a is not available in the given list"

if(b not in li):
    print "eg2:b is not available in the given list"
else:
    print "eg2:b is available in the given list"

执行以上代码,显示结果如下:

C:\Python27\python.exe E:/python/day2test.py
eg1:a is available in the given list
eg2:b is not available in the given list

 6、二进制位运算符

代码说明:

# !/usr/bin/env python
# -*-coding:utf-8-*-
# __author__ = "tina"

a=60
b=13
c=0

c = a & b
print "eg1:Value of c is ", c

c = a | b
print "eg2:Value of c is ", c

c = a ^ b
print "eg3:Value of c is ", c

c = ~a
print "eg4:Value of c is ", c

c = a << 2
print "eg5:Value of c is ", c

c = a >> 2
print "eg6:Value of c is ", c

执行以上代码,显示结果如下:

C:\Python27\python.exe E:/python/day2test.py
eg1:Value of c is  12
eg2:Value of c is  61
eg3:Value of c is  49
eg4:Value of c is  -61
eg5:Value of c is  240
eg6:Value of c is  15

 part3——python中的基本数据类型

1、数字

int()整型

>>> help(int)   
Help on class int in module __builtin__:   
class int(object)   
 |  int(x[, base]) -> integer   
 |     
 |  Convert a string or number to an integer, if possible.  A floating point   
 |  argument will be truncated towards zero (this does not include a string   
 |  representation of a floating point number!)  When converting a string, use   
 |  the optional base.  It is an error to supply a base when converting a   
 |  non-string.  If base is zero, the proper base is guessed based on the   
 |  string content.  If the argument is outside the integer range a   
 |  long object will be returned instead.  
  1 class int(object):
  2     """
  3     int(x=0) -> int or long
  4     int(x, base=10) -> int or long
  5     
  6     Convert a number or string to an integer, or return 0 if no arguments
  7     are given.  If x is floating point, the conversion truncates towards zero.
  8     If x is outside the integer range, the function returns a long instead.
  9     
 10     If x is not a number or if base is given, then x must be a string or
 11     Unicode object representing an integer literal in the given base.  The
 12     literal can be preceded by '+' or '-' and be surrounded by whitespace.
 13     The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 14     interpret the base from the string as an integer literal.
 15     >>> int('0b100', base=0)
 16     4
 17     """
 18     def bit_length(self): # real signature unknown; restored from __doc__
 19         """
 20         int.bit_length() -> int
 21         
 22         Number of bits necessary to represent self in binary.
 23         >>> bin(37)
 24         '0b100101'
 25         >>> (37).bit_length()
 26         6
 27         """
 28         return 0
 29 
 30     def conjugate(self, *args, **kwargs): # real signature unknown
 31         """ Returns self, the complex conjugate of any int. """
 32         pass
 33 
 34     def __abs__(self): # real signature unknown; restored from __doc__
 35         """ x.__abs__() <==> abs(x) """
 36         pass
 37 
 38     def __add__(self, y): # real signature unknown; restored from __doc__
 39         """ x.__add__(y) <==> x+y """
 40         pass
 41 
 42     def __and__(self, y): # real signature unknown; restored from __doc__
 43         """ x.__and__(y) <==> x&y """
 44         pass
 45 
 46     def __cmp__(self, y): # real signature unknown; restored from __doc__
 47         """ x.__cmp__(y) <==> cmp(x,y) """
 48         pass
 49 
 50     def __coerce__(self, y): # real signature unknown; restored from __doc__
 51         """ x.__coerce__(y) <==> coerce(x, y) """
 52         pass
 53 
 54     def __divmod__(self, y): # real signature unknown; restored from __doc__
 55         """ x.__divmod__(y) <==> divmod(x, y) """
 56         pass
 57 
 58     def __div__(self, y): # real signature unknown; restored from __doc__
 59         """ x.__div__(y) <==> x/y """
 60         pass
 61 
 62     def __float__(self): # real signature unknown; restored from __doc__
 63         """ x.__float__() <==> float(x) """
 64         pass
 65 
 66     def __floordiv__(self, y): # real signature unknown; restored from __doc__
 67         """ x.__floordiv__(y) <==> x//y """
 68         pass
 69 
 70     def __format__(self, *args, **kwargs): # real signature unknown
 71         pass
 72 
 73     def __getattribute__(self, name): # real signature unknown; restored from __doc__
 74         """ x.__getattribute__('name') <==> x.name """
 75         pass
 76 
 77     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 78         pass
 79 
 80     def __hash__(self): # real signature unknown; restored from __doc__
 81         """ x.__hash__() <==> hash(x) """
 82         pass
 83 
 84     def __hex__(self): # real signature unknown; restored from __doc__
 85         """ x.__hex__() <==> hex(x) """
 86         pass
 87 
 88     def __index__(self): # real signature unknown; restored from __doc__
 89         """ x[y:z] <==> x[y.__index__():z.__index__()] """
 90         pass
 91 
 92     def __init__(self, x, base=10): # known special case of int.__init__
 93         """
 94         int(x=0) -> int or long
 95         int(x, base=10) -> int or long
 96         
 97         Convert a number or string to an integer, or return 0 if no arguments
 98         are given.  If x is floating point, the conversion truncates towards zero.
 99         If x is outside the integer range, the function returns a long instead.
100         
101         If x is not a number or if base is given, then x must be a string or
102         Unicode object representing an integer literal in the given base.  The
103         literal can be preceded by '+' or '-' and be surrounded by whitespace.
104         The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
105         interpret the base from the string as an integer literal.
106         >>> int('0b100', base=0)
107         4
108         # (copied from class doc)
109         """
110         pass
111 
112     def __int__(self): # real signature unknown; restored from __doc__
113         """ x.__int__() <==> int(x) """
114         pass
115 
116     def __invert__(self): # real signature unknown; restored from __doc__
117         """ x.__invert__() <==> ~x """
118         pass
119 
120     def __long__(self): # real signature unknown; restored from __doc__
121         """ x.__long__() <==> long(x) """
122         pass
123 
124     def __lshift__(self, y): # real signature unknown; restored from __doc__
125         """ x.__lshift__(y) <==> x<<y """
126         pass
127 
128     def __mod__(self, y): # real signature unknown; restored from __doc__
129         """ x.__mod__(y) <==> x%y """
130         pass
131 
132     def __mul__(self, y): # real signature unknown; restored from __doc__
133         """ x.__mul__(y) <==> x*y """
134         pass
135 
136     def __neg__(self): # real signature unknown; restored from __doc__
137         """ x.__neg__() <==> -x """
138         pass
139 
140     @staticmethod # known case of __new__
141     def __new__(S, *more): # real signature unknown; restored from __doc__
142         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
143         pass
144 
145     def __nonzero__(self): # real signature unknown; restored from __doc__
146         """ x.__nonzero__() <==> x != 0 """
147         pass
148 
149     def __oct__(self): # real signature unknown; restored from __doc__
150         """ x.__oct__() <==> oct(x) """
151         pass
152 
153     def __or__(self, y): # real signature unknown; restored from __doc__
154         """ x.__or__(y) <==> x|y """
155         pass
156 
157     def __pos__(self): # real signature unknown; restored from __doc__
158         """ x.__pos__() <==> +x """
159         pass
160 
161     def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
162         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
163         pass
164 
165     def __radd__(self, y): # real signature unknown; restored from __doc__
166         """ x.__radd__(y) <==> y+x """
167         pass
168 
169     def __rand__(self, y): # real signature unknown; restored from __doc__
170         """ x.__rand__(y) <==> y&x """
171         pass
172 
173     def __rdivmod__(self, y): # real signature unknown; restored from __doc__
174         """ x.__rdivmod__(y) <==> divmod(y, x) """
175         pass
176 
177     def __rdiv__(self, y): # real signature unknown; restored from __doc__
178         """ x.__rdiv__(y) <==> y/x """
179         pass
180 
181     def __repr__(self): # real signature unknown; restored from __doc__
182         """ x.__repr__() <==> repr(x) """
183         pass
184 
185     def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
186         """ x.__rfloordiv__(y) <==> y//x """
187         pass
188 
189     def __rlshift__(self, y): # real signature unknown; restored from __doc__
190         """ x.__rlshift__(y) <==> y<<x """
191         pass
192 
193     def __rmod__(self, y): # real signature unknown; restored from __doc__
194         """ x.__rmod__(y) <==> y%x """
195         pass
196 
197     def __rmul__(self, y): # real signature unknown; restored from __doc__
198         """ x.__rmul__(y) <==> y*x """
199         pass
200 
201     def __ror__(self, y): # real signature unknown; restored from __doc__
202         """ x.__ror__(y) <==> y|x """
203         pass
204 
205     def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
206         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
207         pass
208 
209     def __rrshift__(self, y): # real signature unknown; restored from __doc__
210         """ x.__rrshift__(y) <==> y>>x """
211         pass
212 
213     def __rshift__(self, y): # real signature unknown; restored from __doc__
214         """ x.__rshift__(y) <==> x>>y """
215         pass
216 
217     def __rsub__(self, y): # real signature unknown; restored from __doc__
218         """ x.__rsub__(y) <==> y-x """
219         pass
220 
221     def __rtruediv__(self, y): # real signature unknown; restored from __doc__
222         """ x.__rtruediv__(y) <==> y/x """
223         pass
224 
225     def __rxor__(self, y): # real signature unknown; restored from __doc__
226         """ x.__rxor__(y) <==> y^x """
227         pass
228 
229     def __str__(self): # real signature unknown; restored from __doc__
230         """ x.__str__() <==> str(x) """
231         pass
232 
233     def __sub__(self, y): # real signature unknown; restored from __doc__
234         """ x.__sub__(y) <==> x-y """
235         pass
236 
237     def __truediv__(self, y): # real signature unknown; restored from __doc__
238         """ x.__truediv__(y) <==> x/y """
239         pass
240 
241     def __trunc__(self, *args, **kwargs): # real signature unknown
242         """ Truncating an Integral returns itself. """
243         pass
244 
245     def __xor__(self, y): # real signature unknown; restored from __doc__
246         """ x.__xor__(y) <==> x^y """
247         pass
248 
249     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
250     """the denominator of a rational number in lowest terms"""
251 
252     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
253     """the imaginary part of a complex number"""
254 
255     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
256     """the numerator of a rational number in lowest terms"""
257 
258     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
259     """the real part of a complex number"""
View Code

 一些常用的功能:

bit_length(self)   --->返回表示该数字占用的最少位数

int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6
n1 = 4
n2 = n1.bit_length()
print(n2)

运行结果为3

 

 __add__(self,y)  --->和加号+的作用一样,表示两个数相加

n1=111
n2=222
print(n1+n2)
print(n1__add__(n2))       


运行结果为333

 

__divmod__(self,y) --->相除,得到商和余数组成的元组

a = 9
b = 3
print (a.__divmod__(b))

执行结果为:

(3, 0)

 

__coerce__(self,y) --->强制生成一个元组

a = 9
b = 3
print (a.__coerce__(b))

执行结果为:

(9, 3)

 

__float__(self) --->将数字转换成浮点类型

b = 3
print (b.__float__())

执行结果为:

3.0

__hash__(self)---> 如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。

""" x.__hash__() <==> hash(x) """

2、布尔值

bool(int)

1或0    真或假

布尔值(True or False)可以根据变量的真假值来做出判断,通过代码可以用来控制程序的路径。

class bool(int):
    """
    bool(x) -> bool
    
    Returns True when the argument x is true, False otherwise.
    The builtins True and False are the only two instances of the class bool.
    The class bool is a subclass of the class int, and cannot be subclassed.
    """
    def __and__(self, y): # real signature unknown; restored from __doc__
        """ x.__and__(y) <==> x&y """
        pass

    def __init__(self, x): # real signature unknown; restored from __doc__
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __or__(self, y): # real signature unknown; restored from __doc__
        """ x.__or__(y) <==> x|y """
        pass

    def __rand__(self, y): # real signature unknown; restored from __doc__
        """ x.__rand__(y) <==> y&x """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __ror__(self, y): # real signature unknown; restored from __doc__
        """ x.__ror__(y) <==> y|x """
        pass

    def __rxor__(self, y): # real signature unknown; restored from __doc__
        """ x.__rxor__(y) <==> y^x """
        pass

    def __str__(self): # real signature unknown; restored from __doc__
        """ x.__str__() <==> str(x) """
        pass

    def __xor__(self, y): # real signature unknown; restored from __doc__
        """ x.__xor__(y) <==> x^y """
        pass

 

举例说明:

a = 0
print (bool(a))

b = 1
print (bool(b))

执行结果:

False
True

3、字符串

str()

class str(basestring):
    """
    str(object='') -> string
    
    Return a nice string representation of the object.
    If the argument is a string, the return value is the same object.
    """
    def capitalize(self):  
        """ 首字母变大写 """
        """
        S.capitalize() -> string
        
        Return a copy of the string S with only its first character
        capitalized.
        """
        return ""

    def center(self, width, fillchar=None):  
        """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
        """
        S.center(width[, fillchar]) -> string
        
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def count(self, sub, start=None, end=None):  
        """ 子序列个数 """
        """
        S.count(sub[, start[, end]]) -> int
        
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are interpreted
        as in slice notation.
        """
        return 0

    def decode(self, encoding=None, errors=None):  
        """ 解码 """
        """
        S.decode([encoding[,errors]]) -> object
        
        Decodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that is
        able to handle UnicodeDecodeErrors.
        """
        return object()

    def encode(self, encoding=None, errors=None):  
        """ 编码,针对unicode """
        """
        S.encode([encoding[,errors]]) -> object
        
        Encodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that is able to handle UnicodeEncodeErrors.
        """
        return object()

    def endswith(self, suffix, start=None, end=None):  
        """ 是否以 xxx 结束 """
        """
        S.endswith(suffix[, start[, end]]) -> bool
        
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

    def expandtabs(self, tabsize=None):  
        """ 将tab转换成空格,默认一个tab转换成8个空格 """
        """
        S.expandtabs([tabsize]) -> string
        
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

    def find(self, sub, start=None, end=None):  
        """ 寻找子序列位置,如果没找到,返回 -1 """
        """
        S.find(sub [,start [,end]]) -> int
        
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0

    def format(*args, **kwargs): # known special case of str.format
        """ 字符串格式化,动态参数,将函数式编程时细说 """
        """
        S.format(*args, **kwargs) -> string
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    def index(self, sub, start=None, end=None):  
        """ 子序列位置,如果没找到,报错 """
        S.index(sub [,start [,end]]) -> int
        
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

    def isalnum(self):  
        """ 是否是字母和数字 """
        """
        S.isalnum() -> bool
        
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

    def isalpha(self):  
        """ 是否是字母 """
        """
        S.isalpha() -> bool
        
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

    def isdigit(self):  
        """ 是否是数字 """
        """
        S.isdigit() -> bool
        
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

    def islower(self):  
        """ 是否小写 """
        """
        S.islower() -> bool
        
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def isspace(self):  
        """
        S.isspace() -> bool
        
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

    def istitle(self):  
        """
        S.istitle() -> bool
        
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. uppercase characters may only follow uncased
        characters and lowercase characters only cased ones. Return False
        otherwise.
        """
        return False

    def isupper(self):  
        """
        S.isupper() -> bool
        
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def join(self, iterable):  
        """ 连接 """
        """
        S.join(iterable) -> string
        
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

    def ljust(self, width, fillchar=None):  
        """ 内容左对齐,右侧填充 """
        """
        S.ljust(width[, fillchar]) -> string
        
        Return S left-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def lower(self):  
        """ 变小写 """
        """
        S.lower() -> string
        
        Return a copy of the string S converted to lowercase.
        """
        return ""

    def lstrip(self, chars=None):  
        """ 移除左侧空白 """
        """
        S.lstrip([chars]) -> string or unicode
        
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def partition(self, sep):  
        """ 分割,前,中,后三部分 """
        """
        S.partition(sep) -> (head, sep, tail)
        
        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

    def replace(self, old, new, count=None):  
        """ 替换 """
        """
        S.replace(old, new[, count]) -> string
        
        Return a copy of string S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

    def rfind(self, sub, start=None, end=None):  
        """
        S.rfind(sub [,start [,end]]) -> int
        
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0

    def rindex(self, sub, start=None, end=None):  
        """
        S.rindex(sub [,start [,end]]) -> int
        
        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

    def rjust(self, width, fillchar=None):  
        """
        S.rjust(width[, fillchar]) -> string
        
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def rpartition(self, sep):  
        """
        S.rpartition(sep) -> (head, sep, tail)
        
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

    def rsplit(self, sep=None, maxsplit=None):  
        """
        S.rsplit([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string S, using sep as the
        delimiter string, starting at the end of the string and working
        to the front.  If maxsplit is given, at most maxsplit splits are
        done. If sep is not specified or is None, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None):  
        """
        S.rstrip([chars]) -> string or unicode
        
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def split(self, sep=None, maxsplit=None):  
        """ 分割, maxsplit最多分割几次 """
        """
        S.split([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are removed
        from the result.
        """
        return []

    def splitlines(self, keepends=False):  
        """ 根据换行分割 """
        """
        S.splitlines(keepends=False) -> list of strings
        
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

    def startswith(self, prefix, start=None, end=None):  
        """ 是否起始 """
        """
        S.startswith(prefix[, start[, end]]) -> bool
        
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

    def strip(self, chars=None):  
        """ 移除两段空白 """
        """
        S.strip([chars]) -> string or unicode
        
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def swapcase(self):  
        """ 大写变小写,小写变大写 """
        """
        S.swapcase() -> string
        
        Return a copy of the string S with uppercase characters
        converted to lowercase and vice versa.
        """
        return ""

    def title(self):  
        """
        S.title() -> string
        
        Return a titlecased version of S, i.e. words start with uppercase
        characters, all remaining cased characters have lowercase.
        """
        return ""

    def translate(self, table, deletechars=None):  
        """
        转换,需要先做一个对应表,最后一个表示删除字符集合
        intab = "aeiou"
        outtab = "12345"
        trantab = maketrans(intab, outtab)
        str = "this is string example....wow!!!"
        print str.translate(trantab, 'xm')
        """

        """
        S.translate(table [,deletechars]) -> string
        
        Return a copy of the string S, where all characters occurring
        in the optional argument deletechars are removed, and the
        remaining characters have been mapped through the given
        translation table, which must be a string of length 256 or None.
        If the table argument is None, no translation is applied and
        the operation simply removes the characters in deletechars.
        """
        return ""

    def upper(self):  
        """
        S.upper() -> string
        
        Return a copy of the string S converted to uppercase.
        """
        return ""

    def zfill(self, width):  
        """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
        """
        S.zfill(width) -> string
        
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width.  The string S is never truncated.
        """
        return ""

    def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
        pass

    def _formatter_parser(self, *args, **kwargs): # real signature unknown
        pass

    def __add__(self, y):  
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y):  
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y):  
        """ x.__eq__(y) <==> x==y """
        pass

    def __format__(self, format_spec):  
        """
        S.__format__(format_spec) -> string
        
        Return a formatted version of S as described by format_spec.
        """
        return ""

    def __getattribute__(self, name):  
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y):  
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __getslice__(self, i, j):  
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y):  
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y):  
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self):  
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, string=''): # known special case of str.__init__
        """
        str(object='') -> string
        
        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __len__(self):  
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y):  
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y):  
        """ x.__lt__(y) <==> x<y """
        pass

    def __mod__(self, y):  
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, n):  
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more):  
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y):  
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self):  
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmod__(self, y):  
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, n):  
        """ x.__rmul__(n) <==> n*x """
        pass

    def __sizeof__(self):  
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __str__(self):  
        """ x.__str__() <==> str(x) """
        pass

str
string Code

 

字符串的常用功能:

#capitalize()首字母变大写
a = "tina"
b = a.capitalize()
print (b)

#center()居中
a = "tina"
b = a.center(19,"#")
print (b)

#count()统计次数
a = "tiiiiina"
b = a.count("i",0,4)
print (b)
print (a.count("i"))

#endswith()是否以***结尾
temp = "hello!"
b = temp.endswith("!")
print(b)
#startswith()是否以***开头
temp = "hello!"
b = temp.startswith("h")
print(b)

#extendtabs()将tab键转换成空格键,默认一个tab转换成8个空格
content = "I am fall in\tlove with\t666"
print (content)
print (content.expandtabs())
print (content.expandtabs(22))

#find()找到子序列第一次出现的位置,找不到时返回-1(index()功能跟这个类似)
content = "I am fall in\tlove with\t666"
print (content.find("a"))
print (content.find("al",0,11))

#format()字符串的格式化
s = "I am fall {} love with {}"
print (s.format("in","her"))

**************执行结果如下:***********

Tina
########tina#######
3
5
True
True
I am fall in    love with    666
I am fall in    love with       666
I am fall in          love with             666
2
6
I am fall in love with her

字符串必须记住的操作:

  • 移除空白(strip()移除左右两边的空白,lstrip()移除左边的空白,rstrip()移除右边的空白)
a = "  tina  "
print (a.strip())
b = "*tina*"
print (b.strip("*"))       #strip()移除左右两边的空白
print (b.lstrip("*"))      #移除左边的空白
print (b.rstrip("*"))      #移除右边的空白
c = "ti*na"
print (c.strip("*"))

执行结果如下:
tina
tina
tina*
*tina
ti*na

 

  • 分割(split(),partition(),splitlines()根据换行分割,)
content = "I am fall in\tlove with\t666"
print (content.split("\t"))
print (content.split(" "))
content = "I am fall in\nlove with\n666"
print (content.splitlines())
print (content.splitlines(0))
print (content.splitlines(1))
print (content.partition("in"))
print (content.partition(" "))

执行结果如下:
['I am fall in', 'love with', '666']
['I', 'am', 'fall', 'in\tlove', 'with\t666']
['I am fall in', 'love with', '666']
['I am fall in', 'love with', '666']
['I am fall in\n', 'love with\n', '666']
('I am fall ', 'in', '\nlove with\n666')
('I', ' ', 'am fall in\nlove with\n666')

 

  • 长度(len())
temp = "hello!"
print (len(temp))

执行结果:
6

 

  • 索引(str[])
c = "tina"
print (c[0])
print (c[1])
print (c[2])
print (c[3])
#len(c)--->索引(即中括号中的数字)不能超过字符串总长度
执行结果如下: t i n a

 

  • 切片(str[0:2])
c = "tina"
print (c[0:2])

执行结果:
ti

 

4、列表

list[]

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -- append object to end """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
        """
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
        """
        pass

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __delslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__delslice__(i, j) <==> del x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x+=y """
        pass

    def __imul__(self, y): # real signature unknown; restored from __doc__
        """ x.__imul__(y) <==> x*=y """
        pass

    def __init__(self, seq=()): # known special case of list.__init__
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        """
        x.__setslice__(i, j, y) <==> x[i:j]=y
                   
                   Use  of negative indices is not supported.
        """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None

list
list Code

 

列表的表现形式:

1 list1 = ["tina","tom","eric"]
2 list2 = list(["tina","tom","eric"])

 

列表的常用功能:

>>> list = []        #定义一个空列表
>>> list.append(1)        #向列表中添加成员
>>> list.count(2)        #计算2在列表中出现的次数
0
>>> list.extend([2, 3, 5, 4])        #向列表中添加一个列表
>>> list        #列表值被改变
[1, 2, 3, 5, 4]
>>> list.index(5)        #获得5在列表中的位置
3
>>> list.insert(2, 6)        #从0开始,也就是在第3个成员处插入6,其他成员顺次后移
>>> list
[1, 2, 6, 3, 5, 4]
>>> list.pop(2)        #删除列表中第3个成员
6
>>> list
[1, 2, 3, 5, 4]
>>> list.remove(5)       #删除列表中的5
>>> list
[1, 2, 3, 4]
>>> list.reverse()        #颠倒列表的顺序
>>> list
[4, 3, 2, 1]
>>> list.sort()        #将列表中的成员重新排序
>>> list
[1, 2, 3, 4]

*********************************************
举例说明:

#创建一个初始有两个字符串和一个整数的列表

book = ["Python", "Development", 8]   

#在列表尾部添加另一个整数
 book.append(2016)

#在第二个位置上插入一个字符串(下标为1)
 book.insert(1, "web")
 book
['Python', 'web', 'Development', 8, 2016]

#获取头三个元素的一个切片
 book[ : 3]
['Python', 'web', 'Development']

#成员检查
 "Django" in book
False

#无论元素的位置,从列表中移除它。(显式移除对象)
 book.remove(8)

#根据位置(即下标)移除(并返回)一个元素
 book.pop(-1)
2016
book
['Python', 'web', 'Development']

#展示复制操作符*的用法
 book * 2
['Python', 'web', 'Development', 'Python', 'web', 'Development']

#用另一个列表扩展本列表
 book.extend(["with", "Django"])

print(book)
['Python', 'web', 'Development', 'with', 'Django']

 **********************************************

常用列表操作方法

list.append():追加成员

list.count(x):计算列表中参数x出现的次数

list.extend(L):向列表中追加另一个列表L

list.index(x):获得参数x在列表中的位置

list.insert():向列表中插入数据

list.pop():删除列表中的成员(通过下标删除)

list.remove():删除列表中的成员(直接删除)

list.reverse():将列表中成员的顺序颠倒

list.sort():将列表中成员排序

 

列表必须记住的操作:

  • 索引
list2 = list(["tina","tom","eric"])
print (list2[0])
print (list2[1])
执行结果如下:
tina
tom

 

  • 切片
list1 = ["tina","tom","eric"]
print (list1[0:2])
执行结果如下:
['tina', 'tom']

 

  • 追加
list1 = ["tina","tom","eric"]
list1.append('fei')
list1.append('fei')
list1.append('fei')
print (list1)
print (list1.count("fei"))
执行结果如下:
['tina', 'tom', 'eric', 'fei', 'fei', 'fei']
3
#append()一次只能追加一个值,且追加在列表的尾部
#iterable,可迭代的
extend()批量追加
list1 = ["tina","tom","eric"]
temp = [11,22,33,44]
list1.extend(temp)
print (list1)
执行结果如下:
['tina', 'tom', 'eric', 11, 22, 33, 44] 
list1 = ["tina","tom","eric"]
print (list1.index("tina"))
list1.insert(0,"fei")
print (list1)
执行结果如下:
0
['fei', 'tina', 'tom', 'eric']

 

  • 删除(pop()剪切,remove()移除从左边找到的第一个object)
list1 = ["tina","tom","eric"]
print (list1.index("tina"))
list1.insert(0,"fei")
list1.pop()
print (list1)
a = list1.pop()
print (a)
执行结果如下:
0
['fei', 'tina', 'tom']
tom
list1 = ["tina","tom","eric"]
list1.append('fei')
list1.insert(1,'fei')
print (list1)
list1.remove("fei")
print (list1)
执行结果如下:
['tina', 'fei', 'tom', 'eric', 'fei']
['tina', 'tom', 'eric', 'fei']

 

  • 长度
list1 = ["tina","tom","eric"]
print (len(list1))
print (list1[1:len(list1)])
执行结果如下:
3
['tom', 'eric']

 

  • 循环
list1 = ["tina","tom","eric"]
for i in list1:
    print (i)
执行结果如下:
tina
tom
eric

 

  • 包含
list1 = ["tina","tom","eric"]
print ("tina" in list1)
执行结果如下:
True

 

5、元组

tuple()与列表类似,但是列表可修改,元组不可修改(不可增删改操作)

lass tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items
    
    If the argument is a tuple, the return value is the same object.
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self): # real signature unknown; restored from __doc__
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, seq=()): # known special case of tuple.__init__
        """
        tuple() -> empty tuple
        tuple(iterable) -> tuple initialized from iterable's items
        
        If the argument is a tuple, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ T.__sizeof__() -- size of T in memory, in bytes """
        pass

tuple
tuple Code

元组的表现形式:

1 tuple1 = (11,"aa",22,33)
2 tup2 = tuple((11,"aa",22,33))

 

元组的常用功能:

  • 索引
tuple1 = (11,"aa",22,33)
print (tuple1[1])
执行结果如下:
aa

 

  • 切片
tuple1 = (11,"aa",22,33)
print (tuple1[0:1])
执行结果如下:
(11,)

 

  • 长度
tuple1 = (11,"aa",22,33)
print (len(tuple1))
结果:
4

 

  • 循环
tuple1 = (11,"aa",22,33)
for i in tuple1:
    print (i)
执行结果如下:
11
aa
22
33

 

  • 包含
tup2 = tuple((11,"aa",22,33))
print ("aa" in tup2)
执行结果如下:
True

 

6、字典(无序)

字典是一种可变容器模型,可存储任意类型对象。由key,value键值对组成,键必须是唯一的,但值未必,值可以取任何数据类型,但键必须是不可变,如字符串,数字或元组。

class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """

    def clear(self): # real signature unknown; restored from __doc__
        """ 清除内容 """
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ 浅拷贝 """
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(S, v=None): # real signature unknown; restored from __doc__
        """
        dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
        v defaults to None.
        """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根据key获取值,d是默认值 """
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def has_key(self, k): # real signature unknown; restored from __doc__
        """ 是否有key """
        """ D.has_key(k) -> True if D has a key k, else False """
        return False

    def items(self): # real signature unknown; restored from __doc__
        """ 所有项的列表形式 """
        """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
        return []

    def iteritems(self): # real signature unknown; restored from __doc__
        """ 项可迭代 """
        """ D.iteritems() -> an iterator over the (key, value) items of D """
        pass

    def iterkeys(self): # real signature unknown; restored from __doc__
        """ key可迭代 """
        """ D.iterkeys() -> an iterator over the keys of D """
        pass

    def itervalues(self): # real signature unknown; restored from __doc__
        """ value可迭代 """
        """ D.itervalues() -> an iterator over the values of D """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ 所有的key列表 """
        """ D.keys() -> list of D's keys """
        return []

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """ 获取并在字典中移除 """
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self): # real signature unknown; restored from __doc__
        """ 获取并在字典中移除 """
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """ 更新
            {'name':'alex', 'age': 18000}
            [('name','sbsbsb'),]
        """
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k in F: D[k] = F[k]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ 所有的值 """
        """ D.values() -> list of D's values """
        return []

    def viewitems(self): # real signature unknown; restored from __doc__
        """ 所有项,只是将内容保存至view对象中 """
        """ D.viewitems() -> a set-like object providing a view on D's items """
        pass

    def viewkeys(self): # real signature unknown; restored from __doc__
        """ D.viewkeys() -> a set-like object providing a view on D's keys """
        pass

    def viewvalues(self): # real signature unknown; restored from __doc__
        """ D.viewvalues() -> an object providing a view on D's values """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __contains__(self, k): # real signature unknown; restored from __doc__
        """ D.__contains__(k) -> True if D has a key k, else False """
        return False

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

dict
Dict Code

 

字典的表现形式:

1 dict1 = {"name":"tina","age":18}
2 3 dict2 = dict({"name":"tina","age":"18"})

字典的常用功能:

#clear(self)删除字典中的所有元素
p = dict ({"name":"tina","age":18})
print (p)
p.clear()
print (p)
#copy(self)返回一个字典的浅复制
# p.copy()
# print (p)
#fromkeys(S,v=None)创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值
seq = ('name','age','sex')
a = dict.fromkeys(seq)
print (a)
#get(self,k,d=None)返回指定键的值,如果指定键的值不存在时,返回default
p = dict ({"name":"tina","age":18})
a = p.get('name')
print (a)
#has_key(self,k)用于判断键是否存在于字典中,如果键在字典里返回true,否则返回false
p = dict ({"name":"tina","age":18})
a = p.has_key("name")
print (a)
b = p.has_key('gender')
print (b)
#items(self)以列表返回可遍历的(键,值)元组数组
p = dict ({"name":"tina","age":18})
print (p.items())
#iteritems(self)以迭代器的方式返回字典的键和值
p = dict ({"name":"tina","age":18})
print (p.iteritems())
#iterkeys(self)用法类似于iteritems,表示key可迭代
print (p.iterkeys())
#itervalues()value可迭代
print (p.itervalues())
#keys(self)以列表的形式返回一个字典所有的键
print (p.keys())
#values(self)以列表的形式返回字典中所有的值
print (p.values())
#pop(self,k,d=None)删除指定键所对应的值,返回删除键对应的值并移除
print (p.pop('name'))
print (p)
#popitem(self)随机返回并删除字典中的一对键和值,因为字典是无序的,没有所谓的”最后一项”或是其它顺序
print (p.popitem())
print (p)
#setdefault(self,k,d=Nome)如果字典中有指定键,则返回指定键的值,如果没有则创建一个键,值默认为none,值可以指定
w = ({"name":"tina","age":18})
print (w.setdefault("name"))
print (w.setdefault('gender'))
print (w)
#update(self,E=None,**F)把另一个字典中的键值对无序的更新到字典中
t = ({'fruit':'apple','color':'red'})
t.update(w)
print (t)

 

 

part4——其他

1、for循环

li = [11,22,33,44]
for item in li:
    print item

执行结果如下:
11
22
33
44

 

2、enumerate

li = [11,22,33,44,55]
for k,v in enumerate(li, 1):
    print(k,v)

执行结果如下:
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)

 

3、range和xrange

xrang不会一次性把序列全部都存放在内存中,而是用到for循环进行迭代的时候才会一个一个的存到内存中,相当于Python3.5中的range。range在python3.5中就不会一次性的占用那么多空间,他会我需要用到这个序列的时候然后再内存中开辟一块空间给这个序列,不是一次性分完,相当于Python2.7.11中的xrange.

for i in range(6,-1,-1):
    print (i)
执行结果如下:
6
5
4
3
2
1
0

 

part5——练习题

 

1、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

li = [11,22,33,44,55,66,77,88,99,90]
di = {'k1':[],'k2':[]}
for i in li:
    if i>66:
        di["k1"].append(i)
    else:
        di["k2"].append(i)
print(di)
方法二:
li = [11,22,33,44,55,66,77,88,99,90]

dict = {
    'k1':[],
    'k2':[]
}

for n in range(len(li)):
    if li[n] <= 66:
        dict['k1'].append(li[n])
    else:
        dict['k2'].append(li[n])

print(dict.get("k1"))
print(dict.get("k2"))

 

2、查找
查找列表中元素,移动空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
li = ["alec", " Aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}

list1 = list(tu)
list2 = list(dic.values())
newlist = li + list1 + list2
for i in newlist:
    ret = i.strip()
    if (ret.startswith('a') or ret.startswith('A')) and ret.endswith('c'):
        print(ret)
3、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
li = ["手机", "电脑", '鼠标垫', '游艇']
for i,j in enumerate(li,1):
    print(i,j)
inp = input("please input your chose:")
user_chose = int(inp)
print(li[user_chose-1])
执行结果如下:
1 手机
2 电脑
3 鼠标垫
4 游艇
please input your chose:1
手机
4、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
money = 0
car_list = []
m = input('请输入总资产:')
money = int(m)

goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
for i in goods:
    print(i['name'],i['price'])
while True:
    inp = input("请选择商品(Y/y结算):")
    if inp.lower() == "y":
        break
    for j in goods:
        if j['name'] == inp:
            car_list.append(j)
print(car_list)

consumption = 0
for item in car_list:
    t = item['price']
    consumption += t
print(money,consumption)
if consumption > money:
    print('余额不足,请充值!')
else:
    print('购买成功!')
执行结果如下:
请输入总资产:888
电脑 1999
鼠标 10
游艇 20
美女 998
请选择商品(Y/y结算):鼠标
请选择商品(Y/y结算):鼠标
请选择商品(Y/y结算):y
[{'name': '鼠标', 'price': 10}, {'name': '鼠标', 'price': 10}]
888 20
购买成功!
方法二:car_dict(精简购物车内容)
#购物车
money = 0
car_dict = {}
m = input('请输入总资产:')
money = int(m)

goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
for i in goods:
    print(i['name'],i['price'])
while True:
    inp = input("请选择商品(Y/y结算):")
    if inp.lower() == "y":
        break
    for item in goods:
        if item['name'] == inp:
            name = item['name']
            if name in car_dict.keys():
                car_dict[name]['num'] = car_dict[name]['num']+1
            else:
                car_dict[name] = {'num':1,"single_price":item['price']}
print(car_dict)
# {
#     '鼠标':{'single_price':10.'num':1},
#     '电脑': {'single_price': 1999.'num': 9},
# }
consumption = 0
for k,v in car_dict:
    n = v['single_price']
    m = v['num']
    total = n * m
    consumption += total
print(money,consumption)
if consumption > money:
    print('余额不足,请充值!')
else:
    print('购买成功!') 

 5、三级联动

dic = {
"河北":{
"石家庄":['藁城','袁璇','鹿泉'],
'保定':['A县','B县','C县'],
},
"河南":{
"郑州":['新郑区','金水区','上城区'],
'信阳':['羊山新区','浉河区','平桥区'],
},
"湖北":{
"武汉":["软件园",'汉口','武昌'],
'仙桃':['商城','东桥','西桥'],
},
}

 实现让用户层级选择省市区。。。。。(主要考字典嵌套的用法)

dic = {
    "河北":{
        "石家庄":['藁城','袁璇','鹿泉'],
        '保定':['A县','B县','C县'],
    },
    "河南":{
        "郑州":['新郑区','金水区','上城区'],
        '信阳':['羊山新区','浉河区','平桥区'],
    },
    "湖北":{
        "武汉":["软件园",'汉口','武昌'],
        '仙桃':['商城','东桥','西桥'],
    },
}
#循环输出所有的省:
for x in dic:
    print(x)
l1 = input("请输入省份:")
a = dic[l1]
#循环输出所有的市:
for i in a:
    print(i)
l2 = input("请输入市:")
b = dic[l1][l2]
#循环输出所有的区:
for q in b:
    print(q)

执行结果如下:
湖北
河南
河北
请输入省份:河南
郑州
信阳
请输入市:信阳
羊山新区
浉河区
平桥区
请输入区:浉河区

 

posted @ 2016-04-30 13:54  tina.py  阅读(562)  评论(0编辑  收藏  举报