Python基础篇【第三篇】:数据类型

数字数据类型

Python 数字数据类型用于存储数值。

数据类型是不允许改变的,这就意味着如果改变数字数据类型得值,将重新分配内存空间。

支持四种不同的数值类型:

  • int(整型):整型或整数,是正或负整数,不带小数点。
  • long integers(长整型):无限大小的整数,整数最后是一个大写或小写的L。
  • floating point real values(长整型):浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)
  • complex numbers(复数):复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。
  1 #!/usr/bin/env python3
  2 
  3 class int(object):
  4     """
  5     int(x=0) -> integer
  6     int(x, base=10) -> integer
  7 
  8     Convert a number or string to an integer, or return 0 if no arguments
  9     are given.  If x is a number, return x.__int__().  For floating point
 10     numbers, this truncates towards zero.
 11 
 12     If x is not a number or if base is given, then x must be a string,
 13     bytes, or bytearray instance representing an integer literal in the
 14     given base.  The literal can be preceded by '+' or '-' and be surrounded
 15     by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 16     Base 0 means to interpret the base from the string as an integer literal.
 17     >>> int('0b100', base=0)
 18     4
 19     """
 20     def bit_length(self): # real signature unknown; restored from __doc__
 21         """
 22         '''返回表示该数字的时占用的最少位数'''
 23         int.bit_length() -> int
 24 
 25         Number of bits necessary to represent self in binary.
 26         >>> bin(37)
 27         '0b100101'
 28         >>> (37).bit_length()
 29         6
 30         """
 31         return 0
 32 
 33     def conjugate(self, *args, **kwargs): # real signature unknown
 34         '''返回该复数的共轭复数'''
 35         """ Returns self, the complex conjugate of any int. """
 36         pass
 37 
 38     @classmethod # known case
 39     def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
 40         """
 41         int.from_bytes(bytes, byteorder, *, signed=False) -> int
 42 
 43         Return the integer represented by the given array of bytes.
 44 
 45         The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
 46 
 47         The byteorder argument determines the byte order used to represent the
 48         integer.  If byteorder is 'big', the most significant byte is at the
 49         beginning of the byte array.  If byteorder is 'little', the most
 50         significant byte is at the end of the byte array.  To request the native
 51         byte order of the host system, use `sys.byteorder' as the byte order value.
 52 
 53         The signed keyword-only argument indicates whether two's complement is
 54         used to represent the integer.
 55         """
 56         pass
 57 
 58     def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
 59         """
 60         int.to_bytes(length, byteorder, *, signed=False) -> bytes
 61 
 62         Return an array of bytes representing an integer.
 63 
 64         The integer is represented using length bytes.  An OverflowError is
 65         raised if the integer is not representable with the given number of
 66         bytes.
 67 
 68         The byteorder argument determines the byte order used to represent the
 69         integer.  If byteorder is 'big', the most significant byte is at the
 70         beginning of the byte array.  If byteorder is 'little', the most
 71         significant byte is at the end of the byte array.  To request the native
 72         byte order of the host system, use `sys.byteorder' as the byte order value.
 73 
 74         The signed keyword-only argument determines whether two's complement is
 75         used to represent the integer.  If signed is False and a negative integer
 76         is given, an OverflowError is raised.
 77         """
 78         pass
 79 
 80     def __abs__(self, *args, **kwargs): # real signature unknown
 81         '''返回绝对值'''
 82         """ abs(self) """
 83         pass
 84 
 85     def __add__(self, *args, **kwargs): # real signature unknown
 86         """ Return self+value. """
 87         pass
 88 
 89     def __and__(self, *args, **kwargs): # real signature unknown
 90         """ Return self&value. """
 91         pass
 92 
 93     def __bool__(self, *args, **kwargs): # real signature unknown
 94         """ self != 0 """
 95         pass
 96 
 97     def __ceil__(self, *args, **kwargs): # real signature unknown
 98         """ Ceiling of an Integral returns itself. """
 99         pass
100 
101     def __divmod__(self, *args, **kwargs): # real signature unknown
102         '''相除,得到商和余数组成的元组'''
103         """ Return divmod(self, value). """
104         pass
105 
106     def __eq__(self, *args, **kwargs): # real signature unknown
107         """ Return self==value. """
108         pass
109 
110     def __float__(self, *args, **kwargs): # real signature unknown
111         '''转换为浮点类型'''
112         """ float(self) """
113         pass
114 
115     def __floordiv__(self, *args, **kwargs): # real signature unknown
116         """ Return self//value. """
117         pass
118 
119     def __floor__(self, *args, **kwargs): # real signature unknown
120         """ Flooring an Integral returns itself. """
121         pass
122 
123     def __format__(self, *args, **kwargs): # real signature unknown
124         pass
125 
126     def __getattribute__(self, *args, **kwargs): # real signature unknown
127         '''内部调用 __new__方法或创建对象时传入参数使用'''
128         """ Return getattr(self, name). """
129         pass
130 
131     def __getnewargs__(self, *args, **kwargs): # real signature unknown
132         pass
133 
134     def __ge__(self, *args, **kwargs): # real signature unknown
135         """ Return self>=value. """
136         pass
137 
138     def __gt__(self, *args, **kwargs): # real signature unknown
139         """ Return self>value. """
140         pass
141 
142     def __hash__(self, *args, **kwargs): # real signature unknown
143         '''如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。'''
144         """ Return hash(self). """
145         pass
146 
147     def __index__(self, *args, **kwargs): # real signature unknown
148         '''用于切片,数字无意义'''
149         """ Return self converted to an integer, if self is suitable for use as an index into a list. """
150         pass
151 
152     def __init__(self, x, base=10): # known special case of int.__init__
153         '''构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略'''
154         """
155         int(x=0) -> integer
156         int(x, base=10) -> integer
157 
158         Convert a number or string to an integer, or return 0 if no arguments
159         are given.  If x is a number, return x.__int__().  For floating point
160         numbers, this truncates towards zero.
161 
162         If x is not a number or if base is given, then x must be a string,
163         bytes, or bytearray instance representing an integer literal in the
164         given base.  The literal can be preceded by '+' or '-' and be surrounded
165         by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
166         Base 0 means to interpret the base from the string as an integer literal.
167         >>> int('0b100', base=0)
168         4
169         # (copied from class doc)
170         """
171         pass
172 
173     def __int__(self, *args, **kwargs): # real signature unknown
174         '''转换为整数'''
175         """ int(self) """
176         pass
177 
178     def __invert__(self, *args, **kwargs): # real signature unknown
179         """ ~self """
180         pass
181 
182     def __le__(self, *args, **kwargs): # real signature unknown
183         """ Return self<=value. """
184         pass
185 
186     def __lshift__(self, *args, **kwargs): # real signature unknown
187         """ Return self<<value. """
188         pass
189 
190     def __lt__(self, *args, **kwargs): # real signature unknown
191         """ Return self<value. """
192         pass
193 
194     def __mod__(self, *args, **kwargs): # real signature unknown
195         """ Return self%value. """
196         pass
197 
198     def __mul__(self, *args, **kwargs): # real signature unknown
199         """ Return self*value. """
200         pass
201 
202     def __neg__(self, *args, **kwargs): # real signature unknown
203         """ -self """
204         pass
205 
206     @staticmethod # known case of __new__
207     def __new__(*args, **kwargs): # real signature unknown
208         """ Create and return a new object.  See help(type) for accurate signature. """
209         pass
210 
211     def __ne__(self, *args, **kwargs): # real signature unknown
212         """ Return self!=value. """
213         pass
214 
215     def __or__(self, *args, **kwargs): # real signature unknown
216         """ Return self|value. """
217         pass
218 
219     def __pos__(self, *args, **kwargs): # real signature unknown
220         """ +self """
221         pass
222 
223     def __pow__(self, *args, **kwargs): # real signature unknown
224         """ Return pow(self, value, mod). """
225         pass
226 
227     def __radd__(self, *args, **kwargs): # real signature unknown
228         """ Return value+self. """
229         pass
230 
231     def __rand__(self, *args, **kwargs): # real signature unknown
232         """ Return value&self. """
233         pass
234 
235     def __rdivmod__(self, *args, **kwargs): # real signature unknown
236         """ Return divmod(value, self). """
237         pass
238 
239     def __repr__(self, *args, **kwargs): # real signature unknown
240         """ Return repr(self). """
241         pass
242 
243     def __rfloordiv__(self, *args, **kwargs): # real signature unknown
244         """ Return value//self. """
245         pass
246 
247     def __rlshift__(self, *args, **kwargs): # real signature unknown
248         """ Return value<<self. """
249         pass
250 
251     def __rmod__(self, *args, **kwargs): # real signature unknown
252         """ Return value%self. """
253         pass
254 
255     def __rmul__(self, *args, **kwargs): # real signature unknown
256         """ Return value*self. """
257         pass
258 
259     def __ror__(self, *args, **kwargs): # real signature unknown
260         """ Return value|self. """
261         pass
262 
263     def __round__(self, *args, **kwargs): # real signature unknown
264         """
265         Rounding an Integral returns itself.
266         Rounding with an ndigits argument also returns an integer.
267         """
268         pass
269 
270     def __rpow__(self, *args, **kwargs): # real signature unknown
271         """ Return pow(value, self, mod). """
272         pass
273 
274     def __rrshift__(self, *args, **kwargs): # real signature unknown
275         """ Return value>>self. """
276         pass
277 
278     def __rshift__(self, *args, **kwargs): # real signature unknown
279         """ Return self>>value. """
280         pass
281 
282     def __rsub__(self, *args, **kwargs): # real signature unknown
283         """ Return value-self. """
284         pass
285 
286     def __rtruediv__(self, *args, **kwargs): # real signature unknown
287         """ Return value/self. """
288         pass
289 
290     def __rxor__(self, *args, **kwargs): # real signature unknown
291         """ Return value^self. """
292         pass
293 
294     def __sizeof__(self, *args, **kwargs): # real signature unknown
295         """ Returns size in memory, in bytes """
296         pass
297 
298     def __str__(self, *args, **kwargs): # real signature unknown
299         '''转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式'''
300         """ Return str(self). """
301         pass
302 
303     def __sub__(self, *args, **kwargs): # real signature unknown
304         """ Return self-value. """
305         pass
306 
307     def __truediv__(self, *args, **kwargs): # real signature unknown
308         """ Return self/value. """
309         pass
310 
311     def __trunc__(self, *args, **kwargs): # real signature unknown
312         """ Truncating an Integral returns itself. """
313         pass
314 
315     def __xor__(self, *args, **kwargs): # real signature unknown
316         """ Return self^value. """
317         pass
318 
319     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
320     """the denominator of a rational number in lowest terms"""
321 
322     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
323     """the imaginary part of a complex number"""
324 
325     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
326     """the numerator of a rational number in lowest terms"""
327 
328     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
329     """the real part of a complex number"""
int(整型)

以上函数常用的有:

函数返回值 ( 描述 )
abs(x) 返回数字的绝对值,如abs(-10) 返回 10
ceil(x)  返回数字的上入整数,如math.ceil(4.1) 返回 5

cmp(x, y)

如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 Python 3 已废弃 。使用 使用 (x>y)-(x<y) 替换。 
exp(x)  返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0
floor(x)  返回数字的下舍整数,如math.floor(4.9)返回 4
log(x)  如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x)  返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,...)  返回给定参数的最大值,参数可以为序列。
min(x1, x2,...)  返回给定参数的最小值,参数可以为序列。
modf(x)  返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y) x**y 运算后的值。
round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。
sqrt(x)  返回数字x的平方根,数字可以为负数,返回类型为实数,如math.sqrt(4)返回 2+0j

布尔值

真或假

1或0

字符串

字符串的表示形式一般为用''或者""来表示,例如'abc'或者"abc"

字符串常用的功能:

  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片
  1 #!/usr/bin/env python3
  2 
  3 str
  4 
  5 class str(object):
  6     """
  7     str(object='') -> str
  8     str(bytes_or_buffer[, encoding[, errors]]) -> str
  9 
 10     Create a new string object from the given object. If encoding or
 11     errors is specified, then the object must expose a data buffer
 12     that will be decoded using the given encoding and error handler.
 13     Otherwise, returns the result of object.__str__() (if defined)
 14     or repr(object).
 15     encoding defaults to sys.getdefaultencoding().
 16     errors defaults to 'strict'.
 17     """
 18     def capitalize(self): # real signature unknown; restored from __doc__
 19         '''将字符串的第一个字符转换为大写'''
 20         """
 21         S.capitalize() -> str
 22 
 23         Return a capitalized version of S, i.e. make the first character
 24         have upper case and the rest lower case.
 25         """
 26         return ""
 27 
 28     def casefold(self): # real signature unknown; restored from __doc__
 29         """
 30         S.casefold() -> str
 31 
 32         Return a version of S suitable for caseless comparisons.
 33         """
 34         return ""
 35 
 36     def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
 37         '''返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。'''
 38         """
 39         S.center(width[, fillchar]) -> str
 40 
 41         Return S centered in a string of length width. Padding is
 42         done using the specified fill character (default is a space)
 43         """
 44         return ""
 45 
 46     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 47         '''返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
 48 '''
 49         """
 50         S.count(sub[, start[, end]]) -> int
 51 
 52         Return the number of non-overlapping occurrences of substring sub in
 53         string S[start:end].  Optional arguments start and end are
 54         interpreted as in slice notation.
 55         """
 56         return 0
 57 
 58     def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
 59         '''以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'''
 60         """
 61         S.encode(encoding='utf-8', errors='strict') -> bytes
 62 
 63         Encode S using the codec registered for encoding. Default encoding
 64         is 'utf-8'. errors may be given to set a different error
 65         handling scheme. Default is 'strict' meaning that encoding errors raise
 66         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 67         'xmlcharrefreplace' as well as any other name registered with
 68         codecs.register_error that can handle UnicodeEncodeErrors.
 69         """
 70         return b""
 71 
 72     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
 73         '''检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.'''
 74         """
 75         S.endswith(suffix[, start[, end]]) -> bool
 76 
 77         Return True if S ends with the specified suffix, False otherwise.
 78         With optional start, test S beginning at that position.
 79         With optional end, stop comparing S at that position.
 80         suffix can also be a tuple of strings to try.
 81         """
 82         return False
 83 
 84     def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
 85         '''把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。'''
 86         """
 87         S.expandtabs(tabsize=8) -> str
 88 
 89         Return a copy of S where all tab characters are expanded using spaces.
 90         If tabsize is not given, a tab size of 8 characters is assumed.
 91         """
 92         return ""
 93 
 94     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 95         '''检测 str 是否包含在字符串中 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1 '''
 96 
 97         """
 98         S.find(sub[, start[, end]]) -> int
 99 
100         Return the lowest index in S where substring sub is found,
101         such that sub is contained within S[start:end].  Optional
102         arguments start and end are interpreted as in slice notation.
103 
104         Return -1 on failure.
105         """
106         return 0
107 
108     def format(*args, **kwargs): # known special case of str.format
109         """
110         S.format(*args, **kwargs) -> str
111 
112         Return a formatted version of S, using substitutions from args and kwargs.
113         The substitutions are identified by braces ('{' and '}').
114         """
115         pass
116 
117     def format_map(self, mapping): # real signature unknown; restored from __doc__
118         """
119         S.format_map(mapping) -> str
120 
121         Return a formatted version of S, using substitutions from mapping.
122         The substitutions are identified by braces ('{' and '}').
123         """
124         return ""
125 
126     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
127         '''跟find()方法一样,只不过如果str不在字符串中会报一个异常.'''
128         """
129         S.index(sub[, start[, end]]) -> int
130 
131         Like S.find() but raise ValueError when the substring is not found.
132         """
133         return 0
134 
135     def isalnum(self): # real signature unknown; restored from __doc__
136         '''如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False'''
137         """
138         S.isalnum() -> bool
139 
140         Return True if all characters in S are alphanumeric
141         and there is at least one character in S, False otherwise.
142         """
143         return False
144 
145     def isalpha(self): # real signature unknown; restored from __doc__
146         '''如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False'''
147         """
148         S.isalpha() -> bool
149 
150         Return True if all characters in S are alphabetic
151         and there is at least one character in S, False otherwise.
152         """
153         return False
154 
155     def isdecimal(self): # real signature unknown; restored from __doc__
156         '''检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。'''
157         """
158         S.isdecimal() -> bool
159 
160         Return True if there are only decimal characters in S,
161         False otherwise.
162         """
163         return False
164 
165     def isdigit(self): # real signature unknown; restored from __doc__
166         '''如果字符串只包含数字则返回 True 否则返回 False..'''
167         """
168         S.isdigit() -> bool
169 
170         Return True if all characters in S are digits
171         and there is at least one character in S, False otherwise.
172         """
173         return False
174 
175     def isidentifier(self): # real signature unknown; restored from __doc__
176         """
177         S.isidentifier() -> bool
178 
179         Return True if S is a valid identifier according
180         to the language definition.
181 
182         Use keyword.iskeyword() to test for reserved identifiers
183         such as "def" and "class".
184         """
185         return False
186 
187     def islower(self): # real signature unknown; restored from __doc__
188         '''如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False'''
189         """
190         S.islower() -> bool
191 
192         Return True if all cased characters in S are lowercase and there is
193         at least one cased character in S, False otherwise.
194         """
195         return False
196 
197     def isnumeric(self): # real signature unknown; restored from __doc__
198         '''如果字符串中只包含数字字符,则返回 True,否则返回 False'''
199         """
200         S.isnumeric() -> bool
201 
202         Return True if there are only numeric characters in S,
203         False otherwise.
204         """
205         return False
206 
207     def isprintable(self): # real signature unknown; restored from __doc__
208         """
209         S.isprintable() -> bool
210 
211         Return True if all characters in S are considered
212         printable in repr() or S is empty, False otherwise.
213         """
214         return False
215 
216     def isspace(self): # real signature unknown; restored from __doc__
217         '''如果字符串中只包含空格,则返回 True,否则返回 False.'''
218         """
219         S.isspace() -> bool
220 
221         Return True if all characters in S are whitespace
222         and there is at least one character in S, False otherwise.
223         """
224         return False
225 
226     def istitle(self): # real signature unknown; restored from __doc__
227         '''如果字符串是标题化的(见 title())则返回 True,否则返回 False'''
228         """
229         S.istitle() -> bool
230 
231         Return True if S is a titlecased string and there is at least one
232         character in S, i.e. upper- and titlecase characters may only
233         follow uncased characters and lowercase characters only cased ones.
234         Return False otherwise.
235         """
236         return False
237 
238     def isupper(self): # real signature unknown; restored from __doc__
239         '''如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False'''
240         """
241         S.isupper() -> bool
242 
243         Return True if all cased characters in S are uppercase and there is
244         at least one cased character in S, False otherwise.
245         """
246         return False
247 
248     def join(self, iterable): # real signature unknown; restored from __doc__
249         '''以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串'''
250         """
251         S.join(iterable) -> str
252 
253         Return a string which is the concatenation of the strings in the
254         iterable.  The separator between elements is S.
255         """
256         return ""
257 
258     def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
259         '''返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。'''
260         """
261         S.ljust(width[, fillchar]) -> str
262 
263         Return S left-justified in a Unicode string of length width. Padding is
264         done using the specified fill character (default is a space).
265         """
266         return ""
267 
268     def lower(self): # real signature unknown; restored from __doc__
269         '''转换字符串中所有大写字符为小写.'''
270         """
271         S.lower() -> str
272 
273         Return a copy of the string S converted to lowercase.
274         """
275         return ""
276 
277     def lstrip(self, chars=None): # real signature unknown; restored from __doc__
278         '''截掉字符串左边的空格'''
279         """
280         S.lstrip([chars]) -> str
281 
282         Return a copy of the string S with leading whitespace removed.
283         If chars is given and not None, remove characters in chars instead.
284         """
285         return ""
286 
287     def maketrans(self, *args, **kwargs): # real signature unknown
288         '''创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。'''
289         """
290         Return a translation table usable for str.translate().
291 
292         If there is only one argument, it must be a dictionary mapping Unicode
293         ordinals (integers) or characters to Unicode ordinals, strings or None.
294         Character keys will be then converted to ordinals.
295         If there are two arguments, they must be strings of equal length, and
296         in the resulting dictionary, each character in x will be mapped to the
297         character at the same position in y. If there is a third argument, it
298         must be a string, whose characters will be mapped to None in the result.
299         """
300         pass
301 
302     def partition(self, sep): # real signature unknown; restored from __doc__
303         """
304         S.partition(sep) -> (head, sep, tail)
305 
306         Search for the separator sep in S, and return the part before it,
307         the separator itself, and the part after it.  If the separator is not
308         found, return S and two empty strings.
309         """
310         pass
311 
312     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
313         '''把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。'''
314         """
315         S.replace(old, new[, count]) -> str
316 
317         Return a copy of S with all occurrences of substring
318         old replaced by new.  If the optional argument count is
319         given, only the first count occurrences are replaced.
320         """
321         return ""
322 
323     def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
324         '''类似于 find()函数,不过是从右边开始查找.'''
325         """
326         S.rfind(sub[, start[, end]]) -> int
327 
328         Return the highest index in S where substring sub is found,
329         such that sub is contained within S[start:end].  Optional
330         arguments start and end are interpreted as in slice notation.
331 
332         Return -1 on failure.
333         """
334         return 0
335 
336     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
337         '''类似于 index(),不过是从右边开始.'''
338         """
339         S.rindex(sub[, start[, end]]) -> int
340 
341         Like S.rfind() but raise ValueError when the substring is not found.
342         """
343         return 0
344 
345     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
346         '''返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串'''
347         """
348         S.rjust(width[, fillchar]) -> str
349 
350         Return S right-justified in a string of length width. Padding is
351         done using the specified fill character (default is a space).
352         """
353         return ""
354 
355     def rpartition(self, sep): # real signature unknown; restored from __doc__
356         """
357         S.rpartition(sep) -> (head, sep, tail)
358 
359         Search for the separator sep in S, starting at the end of S, and return
360         the part before it, the separator itself, and the part after it.  If the
361         separator is not found, return two empty strings and S.
362         """
363         pass
364 
365     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
366 
367         """
368         S.rsplit(sep=None, maxsplit=-1) -> list of strings
369 
370         Return a list of the words in S, using sep as the
371         delimiter string, starting at the end of the string and
372         working to the front.  If maxsplit is given, at most maxsplit
373         splits are done. If sep is not specified, any whitespace string
374         is a separator.
375         """
376         return []
377 
378     def rstrip(self, chars=None): # real signature unknown; restored from __doc__
379         '''删除字符串字符串末尾的空格.'''
380         """
381         S.rstrip([chars]) -> str
382 
383         Return a copy of the string S with trailing whitespace removed.
384         If chars is given and not None, remove characters in chars instead.
385         """
386         return ""
387 
388     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
389 
390         """
391         S.split(sep=None, maxsplit=-1) -> list of strings
392 
393         Return a list of the words in S, using sep as the
394         delimiter string.  If maxsplit is given, at most maxsplit
395         splits are done. If sep is not specified or is None, any
396         whitespace string is a separator and empty strings are
397         removed from the result.
398         """
399         return []
400 
401     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
402         """
403         S.splitlines([keepends]) -> list of strings
404 
405         Return a list of the lines in S, breaking at line boundaries.
406         Line breaks are not included in the resulting list unless keepends
407         is given and true.
408         """
409         return []
410 
411     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
412         """
413         S.startswith(prefix[, start[, end]]) -> bool
414 
415         Return True if S starts with the specified prefix, False otherwise.
416         With optional start, test S beginning at that position.
417         With optional end, stop comparing S at that position.
418         prefix can also be a tuple of strings to try.
419         """
420         return False
421 
422     def strip(self, chars=None): # real signature unknown; restored from __doc__
423         '''在字符串上执行 lstrip()和 rstrip()'''
424         """
425         S.strip([chars]) -> str
426 
427         Return a copy of the string S with leading and trailing
428         whitespace removed.
429         If chars is given and not None, remove characters in chars instead.
430         """
431         return ""
432 
433     def swapcase(self): # real signature unknown; restored from __doc__
434         """
435         S.swapcase() -> str
436 
437         Return a copy of S with uppercase characters converted to lowercase
438         and vice versa.
439         """
440         return ""
441 
442     def title(self): # real signature unknown; restored from __doc__
443         '''返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())'''
444         """
445         S.title() -> str
446 
447         Return a titlecased version of S, i.e. words start with title case
448         characters, all remaining cased characters have lower case.
449         """
450         return ""
451 
452     def translate(self, table): # real signature unknown; restored from __doc__
453         """
454         S.translate(table) -> str
455 
456         Return a copy of the string S in which each character has been mapped
457         through the given translation table. The table must implement
458         lookup/indexing via __getitem__, for instance a dictionary or list,
459         mapping Unicode ordinals to Unicode ordinals, strings, or None. If
460         this operation raises LookupError, the character is left untouched.
461         Characters mapped to None are deleted.
462         """
463         return ""
464 
465     def upper(self): # real signature unknown; restored from __doc__
466         '''转换字符串中的小写字母为大写'''
467         """
468         S.upper() -> str
469 
470         Return a copy of S converted to uppercase.
471         """
472         return ""
473 
474     def zfill(self, width): # real signature unknown; restored from __doc__
475         '''返回长度为 width 的字符串,原字符串右对齐,前面填充0'''
476         """
477         S.zfill(width) -> str
478 
479         Pad a numeric string S with zeros on the left, to fill a field
480         of the specified width. The string S is never truncated.
481         """
482         return ""
483 
484     def __add__(self, *args, **kwargs): # real signature unknown
485         """ Return self+value. """
486         pass
487 
488     def __contains__(self, *args, **kwargs): # real signature unknown
489         """ Return key in self. """
490         pass
491 
492     def __eq__(self, *args, **kwargs): # real signature unknown
493         """ Return self==value. """
494         pass
495 
496     def __format__(self, format_spec): # real signature unknown; restored from __doc__
497         """
498         S.__format__(format_spec) -> str
499 
500         Return a formatted version of S as described by format_spec.
501         """
502         return ""
503 
504     def __getattribute__(self, *args, **kwargs): # real signature unknown
505         """ Return getattr(self, name). """
506         pass
507 
508     def __getitem__(self, *args, **kwargs): # real signature unknown
509         """ Return self[key]. """
510         pass
511 
512     def __getnewargs__(self, *args, **kwargs): # real signature unknown
513         pass
514 
515     def __ge__(self, *args, **kwargs): # real signature unknown
516         """ Return self>=value. """
517         pass
518 
519     def __gt__(self, *args, **kwargs): # real signature unknown
520         """ Return self>value. """
521         pass
522 
523     def __hash__(self, *args, **kwargs): # real signature unknown
524         """ Return hash(self). """
525         pass
526 
527     def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
528         """
529         str(object='') -> str
530         str(bytes_or_buffer[, encoding[, errors]]) -> str
531 
532         Create a new string object from the given object. If encoding or
533         errors is specified, then the object must expose a data buffer
534         that will be decoded using the given encoding and error handler.
535         Otherwise, returns the result of object.__str__() (if defined)
536         or repr(object).
537         encoding defaults to sys.getdefaultencoding().
538         errors defaults to 'strict'.
539         # (copied from class doc)
540         """
541         pass
542 
543     def __iter__(self, *args, **kwargs): # real signature unknown
544         """ Implement iter(self). """
545         pass
546 
547     def __len__(self, *args, **kwargs): # real signature unknown
548         """ Return len(self). """
549         pass
550 
551     def __le__(self, *args, **kwargs): # real signature unknown
552         """ Return self<=value. """
553         pass
554 
555     def __lt__(self, *args, **kwargs): # real signature unknown
556         """ Return self<value. """
557         pass
558 
559     def __mod__(self, *args, **kwargs): # real signature unknown
560         """ Return self%value. """
561         pass
562 
563     def __mul__(self, *args, **kwargs): # real signature unknown
564         """ Return self*value.n """
565         pass
566 
567     @staticmethod # known case of __new__
568     def __new__(*args, **kwargs): # real signature unknown
569         """ Create and return a new object.  See help(type) for accurate signature. """
570         pass
571 
572     def __ne__(self, *args, **kwargs): # real signature unknown
573         """ Return self!=value. """
574         pass
575 
576     def __repr__(self, *args, **kwargs): # real signature unknown
577         """ Return repr(self). """
578         pass
579 
580     def __rmod__(self, *args, **kwargs): # real signature unknown
581         """ Return value%self. """
582         pass
583 
584     def __rmul__(self, *args, **kwargs): # real signature unknown
585         """ Return self*value. """
586         pass
587 
588     def __sizeof__(self): # real signature unknown; restored from __doc__
589         """ S.__sizeof__() -> size of S in memory, in bytes """
590         pass
591 
592     def __str__(self, *args, **kwargs): # real signature unknown
593         """ Return str(self). """
594         pass
str(字符串)

以上函数常用的有:

序号方法及描述
1

capitalize()
将字符串的第一个字符转换为大写

2

center(width, fillchar)


返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
3

count(str, beg= 0,end=len(string))


返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
4

decode(encoding='UTF-8',errors='strict')


使用指定编码来解码字符串。默认编码为字符串编码。
5

encode(encoding='UTF-8',errors='strict')


以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'
6

endswith(suffix, beg=0, end=len(string))
检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.

7

expandtabs(tabsize=8)


把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。
8

find(str, beg=0 end=len(string))


检测 str 是否包含在字符串中 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
9

index(str, beg=0, end=len(string))


跟find()方法一样,只不过如果str不在字符串中会报一个异常.
10

isalnum()


如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
11

isalpha()


如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False
12

isdigit()


如果字符串只包含数字则返回 True 否则返回 False..
13

islower()


如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
14

isnumeric()


如果字符串中只包含数字字符,则返回 True,否则返回 False
15

isspace()


如果字符串中只包含空格,则返回 True,否则返回 False.
16

istitle()


如果字符串是标题化的(见 title())则返回 True,否则返回 False
17

isupper()


如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
18

join(seq)


以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
19

len(string)


返回字符串长度
20

ljust(width[, fillchar])


返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
21

lower()


转换字符串中所有大写字符为小写.
22

lstrip()


截掉字符串左边的空格
23

maketrans()


创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
24

max(str)


返回字符串 str 中最大的字母。
25

min(str)


返回字符串 str 中最小的字母。
26

replace(old, new [, max])


把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。
27

rfind(str, beg=0,end=len(string))


类似于 find()函数,不过是从右边开始查找.
28

rindex( str, beg=0, end=len(string))


类似于 index(),不过是从右边开始.
29

rjust(width,[, fillchar])


返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
30

rstrip()


删除字符串字符串末尾的空格.
31

split(str="", num=string.count(str))


num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num 个子字符串
32

splitlines( num=string.count(' '))


按照行分隔,返回一个包含各行作为元素的列表,如果 num 指定则仅切片 num 个行.
33

startswith(str, beg=0,end=len(string))


检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。
34

strip([chars])


在字符串上执行 lstrip()和 rstrip()
35

swapcase()


将字符串中大写转换为小写,小写转换为大写
36

title()


返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
37

translate(table, deletechars="")


根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
38

upper()


转换字符串中的小写字母为大写
39

zfill (width)


返回长度为 width 的字符串,原字符串右对齐,前面填充0
40

isdecimal()


检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。

列表

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

Python有6个序列的内置类型,但最常见的是列表和元组。

序列都可以进行的操作包括索引,切片,加,乘,检查成员。

此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。

列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。

列表的数据项不需要具有相同的类型

例如:

list1 = ['alex','king','kangkang','abc',123]

列表的索引方式和字符串一样都是从0开始的:

1 #!/usr/bin/env python3
2 
3 list1 = ['alex','king','kangkang','abc',123]
4 
5 print(list1[0],list1[3])

运行结果:

1 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/zk/PycharmProjects/old_boy/day02/基本数据类型/列表.py
2 alex abc
3 
4 Process finished with exit code 0

列表的基本操作:索引、切片、追加、删除、长度、切片、循环、包含

  1 #!/usr/bin/env python3
  2 
  3 # list1 = ['alex','king','kangkang','abc',123]
  4 #
  5 # print(list1[0],list1[3])
  6 list
  7 
  8 class list(object):
  9     """
 10     list() -> new empty list
 11     list(iterable) -> new list initialized from iterable's items
 12     """
 13     def append(self, p_object): # real signature unknown; restored from __doc__
 14         '''在列表末尾添加新的对象'''
 15         """ L.append(object) -> None -- append object to end """
 16         pass
 17 
 18     def clear(self): # real signature unknown; restored from __doc__
 19         '''清除选中的列表'''
 20         """ L.clear() -> None -- remove all items from L """
 21         pass
 22 
 23     def copy(self): # real signature unknown; restored from __doc__
 24         '''复制列表'''
 25         """ L.copy() -> list -- a shallow copy of L """
 26         return []
 27 
 28     def count(self, value): # real signature unknown; restored from __doc__
 29         '''统计某个元素在列表中出现的次数'''
 30         """ L.count(value) -> integer -- return number of occurrences of value """
 31         return 0
 32 
 33     def extend(self, iterable): # real signature unknown; restored from __doc__
 34         '''在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)'''
 35         """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
 36         pass
 37 
 38     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 39         '''从列表中找出某个值第一个匹配项的索引位置'''
 40         """
 41         L.index(value, [start, [stop]]) -> integer -- return first index of value.
 42         Raises ValueError if the value is not present.
 43         """
 44         return 0
 45 
 46     def insert(self, index, p_object): # real signature unknown; restored from __doc__
 47         '''将对象插入列表'''
 48         """ L.insert(index, object) -- insert object before index """
 49         pass
 50 
 51     def pop(self, index=None): # real signature unknown; restored from __doc__
 52         '''移除列表中的一个元素(默认最后一个元素),并且返回该元素的值'''
 53         """
 54         L.pop([index]) -> item -- remove and return item at index (default last).
 55         Raises IndexError if list is empty or index is out of range.
 56         """
 57         pass
 58 
 59     def remove(self, value): # real signature unknown; restored from __doc__
 60         '''移除列表中某个值的第一个匹配项'''
 61         """
 62         L.remove(value) -> None -- remove first occurrence of value.
 63         Raises ValueError if the value is not present.
 64         """
 65         pass
 66 
 67     def reverse(self): # real signature unknown; restored from __doc__
 68         '''反向列表中元素'''
 69         """ L.reverse() -- reverse *IN PLACE* """
 70         pass
 71 
 72     def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
 73         '''对原列表进行排序'''
 74         """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
 75         pass
 76 
 77     def __add__(self, *args, **kwargs): # real signature unknown
 78         """ Return self+value. """
 79         pass
 80 
 81     def __contains__(self, *args, **kwargs): # real signature unknown
 82         """ Return key in self. """
 83         pass
 84 
 85     def __delitem__(self, *args, **kwargs): # real signature unknown
 86         """ Delete self[key]. """
 87         pass
 88 
 89     def __eq__(self, *args, **kwargs): # real signature unknown
 90         """ Return self==value. """
 91         pass
 92 
 93     def __getattribute__(self, *args, **kwargs): # real signature unknown
 94         """ Return getattr(self, name). """
 95         pass
 96 
 97     def __getitem__(self, y): # real signature unknown; restored from __doc__
 98         """ x.__getitem__(y) <==> x[y] """
 99         pass
100 
101     def __ge__(self, *args, **kwargs): # real signature unknown
102         """ Return self>=value. """
103         pass
104 
105     def __gt__(self, *args, **kwargs): # real signature unknown
106         """ Return self>value. """
107         pass
108 
109     def __iadd__(self, *args, **kwargs): # real signature unknown
110         """ Implement self+=value. """
111         pass
112 
113     def __imul__(self, *args, **kwargs): # real signature unknown
114         """ Implement self*=value. """
115         pass
116 
117     def __init__(self, seq=()): # known special case of list.__init__
118         """
119         list() -> new empty list
120         list(iterable) -> new list initialized from iterable's items
121         # (copied from class doc)
122         """
123         pass
124 
125     def __iter__(self, *args, **kwargs): # real signature unknown
126         """ Implement iter(self). """
127         pass
128 
129     def __len__(self, *args, **kwargs): # real signature unknown
130         """ Return len(self). """
131         pass
132 
133     def __le__(self, *args, **kwargs): # real signature unknown
134         """ Return self<=value. """
135         pass
136 
137     def __lt__(self, *args, **kwargs): # real signature unknown
138         """ Return self<value. """
139         pass
140 
141     def __mul__(self, *args, **kwargs): # real signature unknown
142         """ Return self*value.n """
143         pass
144 
145     @staticmethod # known case of __new__
146     def __new__(*args, **kwargs): # real signature unknown
147         """ Create and return a new object.  See help(type) for accurate signature. """
148         pass
149 
150     def __ne__(self, *args, **kwargs): # real signature unknown
151         """ Return self!=value. """
152         pass
153 
154     def __repr__(self, *args, **kwargs): # real signature unknown
155         """ Return repr(self). """
156         pass
157 
158     def __reversed__(self): # real signature unknown; restored from __doc__
159         """ L.__reversed__() -- return a reverse iterator over the list """
160         pass
161 
162     def __rmul__(self, *args, **kwargs): # real signature unknown
163         """ Return self*value. """
164         pass
165 
166     def __setitem__(self, *args, **kwargs): # real signature unknown
167         """ Set self[key] to value. """
168         pass
169 
170     def __sizeof__(self): # real signature unknown; restored from __doc__
171         """ L.__sizeof__() -- size of L in memory, in bytes """
172         pass
173 
174     __hash__ = None
list(列表)

以上常用函数:

序号方法
1 list.append(obj)
在列表末尾添加新的对象
2 list.count(obj)
统计某个元素在列表中出现的次数
3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj)
将对象插入列表
6 list.pop(obj=list[-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj)
移除列表中某个值的第一个匹配项
8 list.reverse()
反向列表中元素
9 list.sort([func])
对原列表进行排序
10 list.clear()
清空列表
11 list.copy()
复制列表

元组

Python 的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

tup1 = ('alex','king','kangkang','abc',123)
  1 #!/usr/bin/env python3
  2 
  3 # tup1 = ('alex','king','kangkang','abc',123)
  4 tuple
  5 
  6 class tuple(object):
  7     """
  8     tuple() -> empty tuple
  9     tuple(iterable) -> tuple initialized from iterable's items
 10 
 11     If the argument is a tuple, the return value is the same object.
 12     """
 13     def count(self, value): # real signature unknown; restored from __doc__
 14         '''统计某个元素在元组中出现的次数'''
 15         """ T.count(value) -> integer -- return number of occurrences of value """
 16         return 0
 17 
 18     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 19         '''从元组中找出某个值第一个匹配项的索引位置'''
 20         """
 21         T.index(value, [start, [stop]]) -> integer -- return first index of value.
 22         Raises ValueError if the value is not present.
 23         """
 24         return 0
 25 
 26     def __add__(self, *args, **kwargs): # real signature unknown
 27         """ Return self+value. """
 28         pass
 29 
 30     def __contains__(self, *args, **kwargs): # real signature unknown
 31         """ Return key in self. """
 32         pass
 33 
 34     def __eq__(self, *args, **kwargs): # real signature unknown
 35         """ Return self==value. """
 36         pass
 37 
 38     def __getattribute__(self, *args, **kwargs): # real signature unknown
 39         """ Return getattr(self, name). """
 40         pass
 41 
 42     def __getitem__(self, *args, **kwargs): # real signature unknown
 43         """ Return self[key]. """
 44         pass
 45 
 46     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 47         pass
 48 
 49     def __ge__(self, *args, **kwargs): # real signature unknown
 50         """ Return self>=value. """
 51         pass
 52 
 53     def __gt__(self, *args, **kwargs): # real signature unknown
 54         """ Return self>value. """
 55         pass
 56 
 57     def __hash__(self, *args, **kwargs): # real signature unknown
 58         """ Return hash(self). """
 59         pass
 60 
 61     def __init__(self, seq=()): # known special case of tuple.__init__
 62         """
 63         tuple() -> empty tuple
 64         tuple(iterable) -> tuple initialized from iterable's items
 65 
 66         If the argument is a tuple, the return value is the same object.
 67         # (copied from class doc)
 68         """
 69         pass
 70 
 71     def __iter__(self, *args, **kwargs): # real signature unknown
 72         """ Implement iter(self). """
 73         pass
 74 
 75     def __len__(self, *args, **kwargs): # real signature unknown
 76         '''计算元组元素个数。'''
 77         """ Return len(self). """
 78         pass
 79 
 80     def __le__(self, *args, **kwargs): # real signature unknown
 81         """ Return self<=value. """
 82         pass
 83 
 84     def __lt__(self, *args, **kwargs): # real signature unknown
 85         """ Return self<value. """
 86         pass
 87 
 88     def __mul__(self, *args, **kwargs): # real signature unknown
 89         """ Return self*value.n """
 90         pass
 91 
 92     @staticmethod # known case of __new__
 93     def __new__(*args, **kwargs): # real signature unknown
 94         """ Create and return a new object.  See help(type) for accurate signature. """
 95         pass
 96 
 97     def __ne__(self, *args, **kwargs): # real signature unknown
 98         """ Return self!=value. """
 99         pass
100 
101     def __repr__(self, *args, **kwargs): # real signature unknown
102         """ Return repr(self). """
103         pass
104 
105     def __rmul__(self, *args, **kwargs): # real signature unknown
106         """ Return self*value. """
107         pass
tuple(元组)

字典

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

1 #!/usr/bin/env python3
2 
3 dic1 = {
4     'alex':'good',
5     'wuSIR':'good',
6     'wb':'DSB'
7 }

取值:

1 #!/usr/bin/env python3
2 
3 dic1 = {
4     'alex':'good',
5     'wuSIR':'good',
6     'wb':'DSB'
7 }
8 
9 print(dic1['wb'],dic1['wuSIR'])

结果:

1 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/zk/PycharmProjects/old_boy/day02/基本数据类型/字典.py
2 DSB good
3 
4 Process finished with exit code 0

使用方法:索引、新增、删除、键、值、键值对、循环、长度

  1 #!/usr/bin/env python3
  2 
  3 dic1 = {
  4     'alex':'good',
  5     'wuSIR':'good',
  6     'wb':'DSB'
  7 }
  8 
  9 print(dic1['wb'],dic1['wuSIR'])
 10 
 11 dict
 12 
 13 class dict(object):
 14     """
 15     dict() -> new empty dictionary
 16     dict(mapping) -> new dictionary initialized from a mapping object's
 17         (key, value) pairs
 18     dict(iterable) -> new dictionary initialized as if via:
 19         d = {}
 20         for k, v in iterable:
 21             d[k] = v
 22     dict(**kwargs) -> new dictionary initialized with the name=value pairs
 23         in the keyword argument list.  For example:  dict(one=1, two=2)
 24     """
 25     def clear(self): # real signature unknown; restored from __doc__
 26         '''清除内容'''
 27         """ D.clear() -> None.  Remove all items from D. """
 28         pass
 29 
 30     def copy(self): # real signature unknown; restored from __doc__
 31         '''浅拷贝'''
 32         """ D.copy() -> a shallow copy of D """
 33         pass
 34 
 35     @staticmethod # known case
 36     def fromkeys(*args, **kwargs): # real signature unknown
 37         """ Returns a new dict with keys from iterable and values equal to value. """
 38         pass
 39 
 40     def get(self, k, d=None): # real signature unknown; restored from __doc__
 41         '''根据key获取值,d是默认值'''
 42         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
 43         pass
 44 
 45     def items(self): # real signature unknown; restored from __doc__
 46         '''所有项的列表形式'''
 47         """ D.items() -> a set-like object providing a view on D's items """
 48         pass
 49 
 50     def keys(self): # real signature unknown; restored from __doc__
 51         """ 所有的key列表 """
 52         """ D.keys() -> a set-like object providing a view on D's keys """
 53         pass
 54 
 55     def pop(self, k, d=None): # real signature unknown; restored from __doc__
 56         """ 获取并在字典中移除 """
 57         """
 58         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 59         If key is not found, d is returned if given, otherwise KeyError is raised
 60         """
 61         pass
 62 
 63     def popitem(self): # real signature unknown; restored from __doc__
 64         '''获取并在字典中移除'''
 65         """
 66         D.popitem() -> (k, v), remove and return some (key, value) pair as a
 67         2-tuple; but raise KeyError if D is empty.
 68         """
 69         pass
 70 
 71     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
 72         '''如果key不存在,则创建,如果存在,则返回已存在的值且不修改'''
 73         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
 74         pass
 75 
 76     def update(self, E=None, **F): # known special case of dict.update
 77         '''更新'''
 78         """
 79         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 80         If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 81         If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 82         In either case, this is followed by: for k in F:  D[k] = F[k]
 83         """
 84         pass
 85 
 86     def values(self): # real signature unknown; restored from __doc__
 87         '''所有的值'''
 88         """ D.values() -> an object providing a view on D's values """
 89         pass
 90 
 91     def __contains__(self, *args, **kwargs): # real signature unknown
 92         """ True if D has a key k, else False. """
 93         pass
 94 
 95     def __delitem__(self, *args, **kwargs): # real signature unknown
 96         """ Delete self[key]. """
 97         pass
 98 
 99     def __eq__(self, *args, **kwargs): # real signature unknown
100         """ Return self==value. """
101         pass
102 
103     def __getattribute__(self, *args, **kwargs): # real signature unknown
104         """ Return getattr(self, name). """
105         pass
106 
107     def __getitem__(self, y): # real signature unknown; restored from __doc__
108         """ x.__getitem__(y) <==> x[y] """
109         pass
110 
111     def __ge__(self, *args, **kwargs): # real signature unknown
112         """ Return self>=value. """
113         pass
114 
115     def __gt__(self, *args, **kwargs): # real signature unknown
116         """ Return self>value. """
117         pass
118 
119     def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
120         """
121         dict() -> new empty dictionary
122         dict(mapping) -> new dictionary initialized from a mapping object's
123             (key, value) pairs
124         dict(iterable) -> new dictionary initialized as if via:
125             d = {}
126             for k, v in iterable:
127                 d[k] = v
128         dict(**kwargs) -> new dictionary initialized with the name=value pairs
129             in the keyword argument list.  For example:  dict(one=1, two=2)
130         # (copied from class doc)
131         """
132         pass
133 
134     def __iter__(self, *args, **kwargs): # real signature unknown
135         """ Implement iter(self). """
136         pass
137 
138     def __len__(self, *args, **kwargs): # real signature unknown
139         """ Return len(self). """
140         pass
141 
142     def __le__(self, *args, **kwargs): # real signature unknown
143         """ Return self<=value. """
144         pass
145 
146     def __lt__(self, *args, **kwargs): # real signature unknown
147         """ Return self<value. """
148         pass
149 
150     @staticmethod # known case of __new__
151     def __new__(*args, **kwargs): # real signature unknown
152         """ Create and return a new object.  See help(type) for accurate signature. """
153         pass
154 
155     def __ne__(self, *args, **kwargs): # real signature unknown
156         """ Return self!=value. """
157         pass
158 
159     def __repr__(self, *args, **kwargs): # real signature unknown
160         """ Return repr(self). """
161         pass
162 
163     def __setitem__(self, *args, **kwargs): # real signature unknown
164         """ Set self[key] to value. """
165         pass
166 
167     def __sizeof__(self): # real signature unknown; restored from __doc__
168         """ D.__sizeof__() -> size of D in memory, in bytes """
169         pass
170 
171     __hash__ = None
View Code

内置函数使用方法:

 1 #!/usr/bin/env python3
 2 
 3 dic1 = {
 4     'alex':'good',
 5     'wuSIR':'good',
 6     'wb':'DSB'
 7 }
 8 
 9 print(len(dic1))        #计算字典元素个数,即键的总数
10 
11 print(str(dic1))        #输出字典以可打印的字符串表示
12 
13 print(type(dic1))       #返回输入的变量类型,如果变量是字典就返回字典类型

运行结果:

1 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/zk/PycharmProjects/old_boy/day02/基本数据类型/dic.py
2 3
3 {'wuSIR': 'good', 'alex': 'good', 'wb': 'DSB'}
4 <class 'dict'>
5 
6 Process finished with exit code 0

在字典中包含的常用内置方法:

序号函数及描述
1 radiansdict.clear()
删除字典内所有元素 
2 radiansdict.copy()
返回一个字典的浅复制
3 radiansdict.fromkeys()
创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4 radiansdict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值
5 key in dict
如果键在字典dict里返回true,否则返回false
6 radiansdict.items()
以列表返回可遍历的(键, 值) 元组数组
7 radiansdict.keys()
以列表返回一个字典所有的键
8 radiansdict.setdefault(key, default=None)
和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9 radiansdict.update(dict2)
把字典dict2的键/值对更新到dict里
10 radiansdict.values()
以列表返回字典中的所有值
原文地址:https://www.cnblogs.com/allan-king/p/5450771.html