type函数

利用type()函数可以查看数据的类型,比如说是str类型,在编辑器中写上str,按住ctrl,点击str,

就到了源码定义的部分,所有str的功能都在这里了,同样,对于一个str变量temp,temp.upper(),
按住ctrl,点击temp.upper()也跳到了这个功能的说明部分
所有字符串或者数字、字典等数据类型所具备的方法都存在相对应的类里面

查看对象的类,或对象所具备的功能
1、可以利用type查看类型,利用ctrl+鼠标左键
2、利用dir(对象名字),可以查看该类对象所具有的功能名字
3、help(对象名字)或者help(type(对象名字)),可以查看详细说明
4、直接ctrl+鼠标左键点击方法名字,便会自动定位到功能处

下面是对数据类型中的一些函数进行说明,只说了一些不太好理解的函数
在函数的源码里面,如果括号中只有一个self,就表示不用传参数

dir()函数

    见type函数部分

help()函数

    见type函数部分

强制类型转换

    数据类型(变量),例如,有一个str型变量temp,将其转换成int型:

    int(temp)

数据类型中,字符串、列表、字典无疑是最重要的

数字

int型变量

在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

int型变量的创建:

  • n1 = 123
  • n2 = int(123)

类里面有一个__init__方法,类名()这种形式实际上就是调用了该方法,通过查看源码我们也看到,int('0ff',16),这样可以将16进制转化为10进制,这个知道就好了

还有就是类里面带有下划线的方法是自动调用的,在学习到类的时候会有详述

思考一个问题:n1=123,n2=123与n1=123,n2=n1有何区别?

答:n1=123,n2=123是指向内存中的两块区域,n1=123,n2=n1指向内存中的一块区域,但是在python内部,为了内存优化,在一个数值范围内(-5~257),都是指向一块内存。可以用过id(n1)与id(n2)来查看内存地址

python真的很人性化,之前的一些编程语言,整数大小分为多种,但是在python中,在低版本中,还会考虑数据的长度问题,32位机器: -2**31~2**31 ,64位机器:-2**63~2**63-1,如果超出了这个范围,python内部会自动变为long类型,而long是电脑多牛逼,long就有多大,所以在python中使用int,不用担心长度的限制,但是在3的版本中,就没有这个限制了,int就是无限长了,再也不用考虑长度问题了,爽爆了,看下面:

n = 1234567891012312321312312131231231231231
print(n/2327343993898989893493498239489238483248)

输出:0.5304621466567329
是不是感觉爽爆了,哈哈,我喜欢

int类型常用功能剖析:
1、n1+n2 实际是调用n1.__add__(n2)这个方法
2、bit_length()表示该数字的二进制最少可以占用几位

3、输出十进制数字的二进制用bin()方法,具体参考Python之路【第九篇】



python 的data格式 python中的datatype_python

python 的data格式 python中的datatype_python_02

1 class int(object)
  2  |  int(x=0) -> integer
  3  |  int(x, base=10) -> integer
  4  |  
  5  |  Convert a number or string to an integer, or return 0 if no arguments
  6  |  are given.  If x is a number, return x.__int__().  For floating point
  7  |  numbers, this truncates towards zero.
  8  |  
  9  |  If x is not a number or if base is given, then x must be a string,
 10  |  bytes, or bytearray instance representing an integer literal in the
 11  |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 12  |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 13  |  Base 0 means to interpret the base from the string as an integer literal.
 14  |  >>> int('0b100', base=0)
 15  |  4
 16  |  
 17  |  Methods defined here:
 18  |  
 19  |  __abs__(self, /)
 20  |      abs(self)
 21  |  
 22  |  __add__(self, value, /)
 23  |      Return self+value.
 24  |  
 25  |  __and__(self, value, /)
 26  |      Return self&value.
 27  |  
 28  |  __bool__(self, /)
 29  |      self != 0
 30  |  
 31  |  __ceil__(...)
 32  |      Ceiling of an Integral returns itself.
 33  |  
 34  |  __divmod__(self, value, /)
 35  |      Return divmod(self, value).
 36  |  
 37  |  __eq__(self, value, /)
 38  |      Return self==value.
 39  |  
 40  |  __float__(self, /)
 41  |      float(self)
 42  |  
 43  |  __floor__(...)
 44  |      Flooring an Integral returns itself.
 45  |  
 46  |  __floordiv__(self, value, /)
 47  |      Return self//value.
 48  |  
 49  |  __format__(...)
 50  |      default object formatter
 51  |  
 52  |  __ge__(self, value, /)
 53  |      Return self>=value.
 54  |  
 55  |  __getattribute__(self, name, /)
 56  |      Return getattr(self, name).
 57  |  
 58  |  __getnewargs__(...)
 59  |  
 60  |  __gt__(self, value, /)
 61  |      Return self>value.
 62  |  
 63  |  __hash__(self, /)
 64  |      Return hash(self).
 65  |  
 66  |  __index__(self, /)
 67  |      Return self converted to an integer, if self is suitable for use as an index into a list.
 68  |  
 69  |  __int__(self, /)
 70  |      int(self)
 71  |  
 72  |  __invert__(self, /)
 73  |      ~self
 74  |  
 75  |  __le__(self, value, /)
 76  |      Return self<=value.
 77  |  
 78  |  __lshift__(self, value, /)
 79  |      Return self<<value.
 80  |  
 81  |  __lt__(self, value, /)
 82  |      Return self<value.
 83  |  
 84  |  __mod__(self, value, /)
 85  |      Return self%value.
 86  |  
 87  |  __mul__(self, value, /)
 88  |      Return self*value.
 89  |  
 90  |  __ne__(self, value, /)
 91  |      Return self!=value.
 92  |  
 93  |  __neg__(self, /)
 94  |      -self
 95  |  
 96  |  __new__(*args, **kwargs) from builtins.type
 97  |      Create and return a new object.  See help(type) for accurate signature.
 98  |  
 99  |  __or__(self, value, /)
100  |      Return self|value.
101  |  
102  |  __pos__(self, /)
103  |      +self
104  |  
105  |  __pow__(self, value, mod=None, /)
106  |      Return pow(self, value, mod).
107  |  
108  |  __radd__(self, value, /)
109  |      Return value+self.
110  |  
111  |  __rand__(self, value, /)
112  |      Return value&self.
113  |  
114  |  __rdivmod__(self, value, /)
115  |      Return divmod(value, self).
116  |  
117  |  __repr__(self, /)
118  |      Return repr(self).
119  |  
120  |  __rfloordiv__(self, value, /)
121  |      Return value//self.
122  |  
123  |  __rlshift__(self, value, /)
124  |      Return value<<self.
125  |  
126  |  __rmod__(self, value, /)
127  |      Return value%self.
128  |  
129  |  __rmul__(self, value, /)
130  |      Return value*self.
131  |  
132  |  __ror__(self, value, /)
133  |      Return value|self.
134  |  
135  |  __round__(...)
136  |      Rounding an Integral returns itself.
137  |      Rounding with an ndigits argument also returns an integer.
138  |  
139  |  __rpow__(self, value, mod=None, /)
140  |      Return pow(value, self, mod).
141  |  
142  |  __rrshift__(self, value, /)
143  |      Return value>>self.
144  |  
145  |  __rshift__(self, value, /)
146  |      Return self>>value.
147  |  
148  |  __rsub__(self, value, /)
149  |      Return value-self.
150  |  
151  |  __rtruediv__(self, value, /)
152  |      Return value/self.
153  |  
154  |  __rxor__(self, value, /)
155  |      Return value^self.
156  |  
157  |  __sizeof__(...)
158  |      Returns size in memory, in bytes
159  |  
160  |  __str__(self, /)
161  |      Return str(self).
162  |  
163  |  __sub__(self, value, /)
164  |      Return self-value.
165  |  
166  |  __truediv__(self, value, /)
167  |      Return self/value.
168  |  
169  |  __trunc__(...)
170  |      Truncating an Integral returns itself.
171  |  
172  |  __xor__(self, value, /)
173  |      Return self^value.
174  |  
175  |  bit_length(...)
176  |      int.bit_length() -> int
177  |      
178  |      Number of bits necessary to represent self in binary.
179  |      >>> bin(37)
180  |      '0b100101'
181  |      >>> (37).bit_length()
182  |      6
183  |  
184  |  conjugate(...)
185  |      Returns self, the complex conjugate of any int.
186  |  
187  |  from_bytes(...) from builtins.type
188  |      int.from_bytes(bytes, byteorder, *, signed=False) -> int
189  |      
190  |      Return the integer represented by the given array of bytes.
191  |      
192  |      The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
193  |      
194  |      The byteorder argument determines the byte order used to represent the
195  |      integer.  If byteorder is 'big', the most significant byte is at the
196  |      beginning of the byte array.  If byteorder is 'little', the most
197  |      significant byte is at the end of the byte array.  To request the native
198  |      byte order of the host system, use `sys.byteorder' as the byte order value.
199  |      
200  |      The signed keyword-only argument indicates whether two's complement is
201  |      used to represent the integer.
202  |  
203  |  to_bytes(...)
204  |      int.to_bytes(length, byteorder, *, signed=False) -> bytes
205  |      
206  |      Return an array of bytes representing an integer.
207  |      
208  |      The integer is represented using length bytes.  An OverflowError is
209  |      raised if the integer is not representable with the given number of
210  |      bytes.
211  |      
212  |      The byteorder argument determines the byte order used to represent the
213  |      integer.  If byteorder is 'big', the most significant byte is at the
214  |      beginning of the byte array.  If byteorder is 'little', the most
215  |      significant byte is at the end of the byte array.  To request the native
216  |      byte order of the host system, use `sys.byteorder' as the byte order value.
217  |      
218  |      The signed keyword-only argument determines whether two's complement is
219  |      used to represent the integer.  If signed is False and a negative integer
220  |      is given, an OverflowError is raised.
221  |  
222  |  ----------------------------------------------------------------------
223  |  Data descriptors defined here:
224  |  
225  |  denominator
226  |      the denominator of a rational number in lowest terms
227  |  
228  |  imag
229  |      the imaginary part of a complex number
230  |  
231  |  numerator
232  |      the numerator of a rational number in lowest terms
233  |  
234  |  real
235  |      the real part of a complex number


int


bytes类型:

    在2.7中没有,在3里面才有,将字符转换成字节,返回一个字节的集合,所以说3真的是很强大,具体可以参考Python之路【第九篇】

布尔值

True  真

False   假

字符串(str)

字符串的创建:

s1 = 'asd'
s2 = str()创建一个空字符串
s3 = str('asd')创建一个普通的字符串
s4 = str(字节类型,编码),如b_gbk = bytes(s,encoding='gbk')        str(b_gbk,encoding='gbk')

str类型常用功能剖析:
1、format(),format()中接受的参数,依次传递给字符串中的占位符{0},{1},{2},如:s='hello,{0},I {1} you',s.format('python','love')
最后s就变成hello python,I love you有几个占位符就要给format()传递几个参数
2、join(),如lst=['h','e','l','l','o'],执行'_'.join(lst)后得到h_e_l_l_o
3、lstrip()移除字符串中左边的空格
4、rstrip()移除字符串中右边的空格
5、strip()移除字符串中的左边跟右边的空格
6、partition()将字符串进行分割
7、replace()对指定的内容进行替换
8、split()对字符串进行分割
9、索引 s='abcde',s[0]表示第一个字符,s[1]表示第二个字符,依此类推,len(s)用来获取字符串的长度,即字符个数
10、切片s[n:m] n=<*<m




python 的data格式 python中的datatype_python

python 的data格式 python中的datatype_python_02

1 class str(object)
  2  |  str(object='') -> str
  3  |  str(bytes_or_buffer[, encoding[, errors]]) -> str
  4  |  
  5  |  Create a new string object from the given object. If encoding or
  6  |  errors is specified, then the object must expose a data buffer
  7  |  that will be decoded using the given encoding and error handler.
  8  |  Otherwise, returns the result of object.__str__() (if defined)
  9  |  or repr(object).
 10  |  encoding defaults to sys.getdefaultencoding().
 11  |  errors defaults to 'strict'.
 12  |  
 13  |  Methods defined here:
 14  |  
 15  |  __add__(self, value, /)
 16  |      Return self+value.
 17  |  
 18  |  __contains__(self, key, /)
 19  |      Return key in self.
 20  |  
 21  |  __eq__(self, value, /)
 22  |      Return self==value.
 23  |  
 24  |  __format__(...)
 25  |      S.__format__(format_spec) -> str
 26  |      
 27  |      Return a formatted version of S as described by format_spec.
 28  |  
 29  |  __ge__(self, value, /)
 30  |      Return self>=value.
 31  |  
 32  |  __getattribute__(self, name, /)
 33  |      Return getattr(self, name).
 34  |  
 35  |  __getitem__(self, key, /)
 36  |      Return self[key].
 37  |  
 38  |  __getnewargs__(...)
 39  |  
 40  |  __gt__(self, value, /)
 41  |      Return self>value.
 42  |  
 43  |  __hash__(self, /)
 44  |      Return hash(self).
 45  |  
 46  |  __iter__(self, /)
 47  |      Implement iter(self).
 48  |  
 49  |  __le__(self, value, /)
 50  |      Return self<=value.
 51  |  
 52  |  __len__(self, /)
 53  |      Return len(self).
 54  |  
 55  |  __lt__(self, value, /)
 56  |      Return self<value.
 57  |  
 58  |  __mod__(self, value, /)
 59  |      Return self%value.
 60  |  
 61  |  __mul__(self, value, /)
 62  |      Return self*value.n
 63  |  
 64  |  __ne__(self, value, /)
 65  |      Return self!=value.
 66  |  
 67  |  __new__(*args, **kwargs) from builtins.type
 68  |      Create and return a new object.  See help(type) for accurate signature.
 69  |  
 70  |  __repr__(self, /)
 71  |      Return repr(self).
 72  |  
 73  |  __rmod__(self, value, /)
 74  |      Return value%self.
 75  |  
 76  |  __rmul__(self, value, /)
 77  |      Return self*value.
 78  |  
 79  |  __sizeof__(...)
 80  |      S.__sizeof__() -> size of S in memory, in bytes
 81  |  
 82  |  __str__(self, /)
 83  |      Return str(self).
 84  |  
 85  |  capitalize(...)
 86  |      S.capitalize() -> str
 87  |      
 88  |      Return a capitalized version of S, i.e. make the first character
 89  |      have upper case and the rest lower case.
 90  |  
 91  |  casefold(...)
 92  |      S.casefold() -> str
 93  |      
 94  |      Return a version of S suitable for caseless comparisons.
 95  |  
 96  |  center(...)
 97  |      S.center(width[, fillchar]) -> str
 98  |      
 99  |      Return S centered in a string of length width. Padding is
100  |      done using the specified fill character (default is a space)
101  |  
102  |  count(...)
103  |      S.count(sub[, start[, end]]) -> int
104  |      
105  |      Return the number of non-overlapping occurrences of substring sub in
106  |      string S[start:end].  Optional arguments start and end are
107  |      interpreted as in slice notation.
108  |  
109  |  encode(...)
110  |      S.encode(encoding='utf-8', errors='strict') -> bytes
111  |      
112  |      Encode S using the codec registered for encoding. Default encoding
113  |      is 'utf-8'. errors may be given to set a different error
114  |      handling scheme. Default is 'strict' meaning that encoding errors raise
115  |      a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
116  |      'xmlcharrefreplace' as well as any other name registered with
117  |      codecs.register_error that can handle UnicodeEncodeErrors.
118  |  
119  |  endswith(...)
120  |      S.endswith(suffix[, start[, end]]) -> bool
121  |      
122  |      Return True if S ends with the specified suffix, False otherwise.
123  |      With optional start, test S beginning at that position.
124  |      With optional end, stop comparing S at that position.
125  |      suffix can also be a tuple of strings to try.
126  |  
127  |  expandtabs(...)
128  |      S.expandtabs(tabsize=8) -> str
129  |      
130  |      Return a copy of S where all tab characters are expanded using spaces.
131  |      If tabsize is not given, a tab size of 8 characters is assumed.
132  |  
133  |  find(...)
134  |      S.find(sub[, start[, end]]) -> int
135  |      
136  |      Return the lowest index in S where substring sub is found,
137  |      such that sub is contained within S[start:end].  Optional
138  |      arguments start and end are interpreted as in slice notation.
139  |      
140  |      Return -1 on failure.
141  |  
142  |  format(...)
143  |      S.format(*args, **kwargs) -> str
144  |      
145  |      Return a formatted version of S, using substitutions from args and kwargs.
146  |      The substitutions are identified by braces ('{' and '}').
147  |  
148  |  format_map(...)
149  |      S.format_map(mapping) -> str
150  |      
151  |      Return a formatted version of S, using substitutions from mapping.
152  |      The substitutions are identified by braces ('{' and '}').
153  |  
154  |  index(...)
155  |      S.index(sub[, start[, end]]) -> int
156  |      
157  |      Like S.find() but raise ValueError when the substring is not found.
158  |  
159  |  isalnum(...)
160  |      S.isalnum() -> bool
161  |      
162  |      Return True if all characters in S are alphanumeric
163  |      and there is at least one character in S, False otherwise.
164  |  
165  |  isalpha(...)
166  |      S.isalpha() -> bool
167  |      
168  |      Return True if all characters in S are alphabetic
169  |      and there is at least one character in S, False otherwise.
170  |  
171  |  isdecimal(...)
172  |      S.isdecimal() -> bool
173  |      
174  |      Return True if there are only decimal characters in S,
175  |      False otherwise.
176  |  
177  |  isdigit(...)
178  |      S.isdigit() -> bool
179  |      
180  |      Return True if all characters in S are digits
181  |      and there is at least one character in S, False otherwise.
182  |  
183  |  isidentifier(...)
184  |      S.isidentifier() -> bool
185  |      
186  |      Return True if S is a valid identifier according
187  |      to the language definition.
188  |      
189  |      Use keyword.iskeyword() to test for reserved identifiers
190  |      such as "def" and "class".
191  |  
192  |  islower(...)
193  |      S.islower() -> bool
194  |      
195  |      Return True if all cased characters in S are lowercase and there is
196  |      at least one cased character in S, False otherwise.
197  |  
198  |  isnumeric(...)
199  |      S.isnumeric() -> bool
200  |      
201  |      Return True if there are only numeric characters in S,
202  |      False otherwise.
203  |  
204  |  isprintable(...)
205  |      S.isprintable() -> bool
206  |      
207  |      Return True if all characters in S are considered
208  |      printable in repr() or S is empty, False otherwise.
209  |  
210  |  isspace(...)
211  |      S.isspace() -> bool
212  |      
213  |      Return True if all characters in S are whitespace
214  |      and there is at least one character in S, False otherwise.
215  |  
216  |  istitle(...)
217  |      S.istitle() -> bool
218  |      
219  |      Return True if S is a titlecased string and there is at least one
220  |      character in S, i.e. upper- and titlecase characters may only
221  |      follow uncased characters and lowercase characters only cased ones.
222  |      Return False otherwise.
223  |  
224  |  isupper(...)
225  |      S.isupper() -> bool
226  |      
227  |      Return True if all cased characters in S are uppercase and there is
228  |      at least one cased character in S, False otherwise.
229  |  
230  |  join(...)
231  |      S.join(iterable) -> str
232  |      
233  |      Return a string which is the concatenation of the strings in the
234  |      iterable.  The separator between elements is S.
235  |  
236  |  ljust(...)
237  |      S.ljust(width[, fillchar]) -> str
238  |      
239  |      Return S left-justified in a Unicode string of length width. Padding is
240  |      done using the specified fill character (default is a space).
241  |  
242  |  lower(...)
243  |      S.lower() -> str
244  |      
245  |      Return a copy of the string S converted to lowercase.
246  |  
247  |  lstrip(...)
248  |      S.lstrip([chars]) -> str
249  |      
250  |      Return a copy of the string S with leading whitespace removed.
251  |      If chars is given and not None, remove characters in chars instead.
252  |  
253  |  partition(...)
254  |      S.partition(sep) -> (head, sep, tail)
255  |      
256  |      Search for the separator sep in S, and return the part before it,
257  |      the separator itself, and the part after it.  If the separator is not
258  |      found, return S and two empty strings.
259  |  
260  |  replace(...)
261  |      S.replace(old, new[, count]) -> str
262  |      
263  |      Return a copy of S with all occurrences of substring
264  |      old replaced by new.  If the optional argument count is
265  |      given, only the first count occurrences are replaced.
266  |  
267  |  rfind(...)
268  |      S.rfind(sub[, start[, end]]) -> int
269  |      
270  |      Return the highest index in S where substring sub is found,
271  |      such that sub is contained within S[start:end].  Optional
272  |      arguments start and end are interpreted as in slice notation.
273  |      
274  |      Return -1 on failure.
275  |  
276  |  rindex(...)
277  |      S.rindex(sub[, start[, end]]) -> int
278  |      
279  |      Like S.rfind() but raise ValueError when the substring is not found.
280  |  
281  |  rjust(...)
282  |      S.rjust(width[, fillchar]) -> str
283  |      
284  |      Return S right-justified in a string of length width. Padding is
285  |      done using the specified fill character (default is a space).
286  |  
287  |  rpartition(...)
288  |      S.rpartition(sep) -> (head, sep, tail)
289  |      
290  |      Search for the separator sep in S, starting at the end of S, and return
291  |      the part before it, the separator itself, and the part after it.  If the
292  |      separator is not found, return two empty strings and S.
293  |  
294  |  rsplit(...)
295  |      S.rsplit(sep=None, maxsplit=-1) -> list of strings
296  |      
297  |      Return a list of the words in S, using sep as the
298  |      delimiter string, starting at the end of the string and
299  |      working to the front.  If maxsplit is given, at most maxsplit
300  |      splits are done. If sep is not specified, any whitespace string
301  |      is a separator.
302  |  
303  |  rstrip(...)
304  |      S.rstrip([chars]) -> str
305  |      
306  |      Return a copy of the string S with trailing whitespace removed.
307  |      If chars is given and not None, remove characters in chars instead.
308  |  
309  |  split(...)
310  |      S.split(sep=None, maxsplit=-1) -> list of strings
311  |      
312  |      Return a list of the words in S, using sep as the
313  |      delimiter string.  If maxsplit is given, at most maxsplit
314  |      splits are done. If sep is not specified or is None, any
315  |      whitespace string is a separator and empty strings are
316  |      removed from the result.
317  |  
318  |  splitlines(...)
319  |      S.splitlines([keepends]) -> list of strings
320  |      
321  |      Return a list of the lines in S, breaking at line boundaries.
322  |      Line breaks are not included in the resulting list unless keepends
323  |      is given and true.
324  |  
325  |  startswith(...)
326  |      S.startswith(prefix[, start[, end]]) -> bool
327  |      
328  |      Return True if S starts with the specified prefix, False otherwise.
329  |      With optional start, test S beginning at that position.
330  |      With optional end, stop comparing S at that position.
331  |      prefix can also be a tuple of strings to try.
332  |  
333  |  strip(...)
334  |      S.strip([chars]) -> str
335  |      
336  |      Return a copy of the string S with leading and trailing
337  |      whitespace removed.
338  |      If chars is given and not None, remove characters in chars instead.
339  |  
340  |  swapcase(...)
341  |      S.swapcase() -> str
342  |      
343  |      Return a copy of S with uppercase characters converted to lowercase
344  |      and vice versa.
345  |  
346  |  title(...)
347  |      S.title() -> str
348  |      
349  |      Return a titlecased version of S, i.e. words start with title case
350  |      characters, all remaining cased characters have lower case.
351  |  
352  |  translate(...)
353  |      S.translate(table) -> str
354  |      
355  |      Return a copy of the string S in which each character has been mapped
356  |      through the given translation table. The table must implement
357  |      lookup/indexing via __getitem__, for instance a dictionary or list,
358  |      mapping Unicode ordinals to Unicode ordinals, strings, or None. If
359  |      this operation raises LookupError, the character is left untouched.
360  |      Characters mapped to None are deleted.
361  |  
362  |  upper(...)
363  |      S.upper() -> str
364  |      
365  |      Return a copy of S converted to uppercase.
366  |  
367  |  zfill(...)
368  |      S.zfill(width) -> str
369  |      
370  |      Pad a numeric string S with zeros on the left, to fill a field
371  |      of the specified width. The string S is never truncated.
372  |  
373  |  ----------------------------------------------------------------------
374  |  Static methods defined here:
375  |  
376  |  maketrans(x, y=None, z=None, /)
377  |      Return a translation table usable for str.translate().
378  |      
379  |      If there is only one argument, it must be a dictionary mapping Unicode
380  |      ordinals (integers) or characters to Unicode ordinals, strings or None.
381  |      Character keys will be then converted to ordinals.
382  |      If there are two arguments, they must be strings of equal length, and
383  |      in the resulting dictionary, each character in x will be mapped to the
384  |      character at the same position in y. If there is a third argument, it
385  |      must be a string, whose characters will be mapped to None in the result.


str


 

列表(list)

     列表是元素的集合,并且列表中的元素是可变化的

在以后的日子里,有一个约定俗成的东西,写列表的时候最后加一个逗号,比如:[1,2,3,4,5,]

列表的创建;

  li = [1,2,3,4,]

  li = list(),创建一个空的列表

  li = list(可迭代对象),转换,字符串、元组、字典都是可迭代对象,比如这里的可迭代对象是一个字符串,内部会运行一个for循环,把可迭代对象的元素当作列表的元素,如:  

 



s = 'hello'
li = list(s)
print(li)
输出结果为:['h', 'e', 'l', 'l', 'o']



dic = {'k1':'as','k2':'dasd'}
print(list(dic.values()))
print(list(dic.items()))
print(list(dic.keys()))
输出结果为:

['dasd', 'as']
[('k2', 'dasd'), ('k1', 'as')]
['k2', 'k1']



 

list类型常用功能剖析:
lst = [1,2,3,'e'],这就是一个列表
len(lst)获取列表长度
列表中的索引、切片、循环跟字符串都是一样的
append(),在列表末尾追加元素,lst.append('s'),则lst=[***,'s']
count(),统计列表中某一个元素的个数
extend(),扩展列表,lst.extend(iterable),iterable为可迭代对象
index(),获取某个元素的索引
insert(),往某个索引位置插入一个值
pop(),移除一个值,没有参数的,移除尾部的值,但是这个值可以赋给另外一个变量,如a=lst.pop(),就表示将列表中的最后一个元素移除并赋值给a
remove(),移除从左边找到的第一个
reverse(),反转列表
sort()排序
del lst[index]删除索引index处的元素,del lst[index1:index2]

列表的嵌套:li = ['alex',123,{'k1':123,'k2':{'aa':1,'bb':2}}]

列表的切片与索引




python 的data格式 python中的datatype_python

python 的data格式 python中的datatype_python_02

1 class list(object)
  2  |  list() -> new empty list
  3  |  list(iterable) -> new list initialized from iterable's items
  4  |  
  5  |  Methods defined here:
  6  |  
  7  |  __add__(self, value, /)
  8  |      Return self+value.
  9  |  
 10  |  __contains__(self, key, /)
 11  |      Return key in self.
 12  |  
 13  |  __delitem__(self, key, /)
 14  |      Delete self[key].
 15  |  
 16  |  __eq__(self, value, /)
 17  |      Return self==value.
 18  |  
 19  |  __ge__(self, value, /)
 20  |      Return self>=value.
 21  |  
 22  |  __getattribute__(self, name, /)
 23  |      Return getattr(self, name).
 24  |  
 25  |  __getitem__(...)
 26  |      x.__getitem__(y) <==> x[y]
 27  |  
 28  |  __gt__(self, value, /)
 29  |      Return self>value.
 30  |  
 31  |  __iadd__(self, value, /)
 32  |      Implement self+=value.
 33  |  
 34  |  __imul__(self, value, /)
 35  |      Implement self*=value.
 36  |  
 37  |  __init__(self, /, *args, **kwargs)
 38  |      Initialize self.  See help(type(self)) for accurate signature.
 39  |  
 40  |  __iter__(self, /)
 41  |      Implement iter(self).
 42  |  
 43  |  __le__(self, value, /)
 44  |      Return self<=value.
 45  |  
 46  |  __len__(self, /)
 47  |      Return len(self).
 48  |  
 49  |  __lt__(self, value, /)
 50  |      Return self<value.
 51  |  
 52  |  __mul__(self, value, /)
 53  |      Return self*value.n
 54  |  
 55  |  __ne__(self, value, /)
 56  |      Return self!=value.
 57  |  
 58  |  __new__(*args, **kwargs) from builtins.type
 59  |      Create and return a new object.  See help(type) for accurate signature.
 60  |  
 61  |  __repr__(self, /)
 62  |      Return repr(self).
 63  |  
 64  |  __reversed__(...)
 65  |      L.__reversed__() -- return a reverse iterator over the list
 66  |  
 67  |  __rmul__(self, value, /)
 68  |      Return self*value.
 69  |  
 70  |  __setitem__(self, key, value, /)
 71  |      Set self[key] to value.
 72  |  
 73  |  __sizeof__(...)
 74  |      L.__sizeof__() -- size of L in memory, in bytes
 75  |  
 76  |  append(...)
 77  |      L.append(object) -> None -- append object to end
 78  |  
 79  |  clear(...)
 80  |      L.clear() -> None -- remove all items from L
 81  |  
 82  |  copy(...)
 83  |      L.copy() -> list -- a shallow copy of L
 84  |  
 85  |  count(...)
 86  |      L.count(value) -> integer -- return number of occurrences of value
 87  |  
 88  |  extend(...)
 89  |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 90  |  
 91  |  index(...)
 92  |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 93  |      Raises ValueError if the value is not present.
 94  |  
 95  |  insert(...)
 96  |      L.insert(index, object) -- insert object before index
 97  |  
 98  |  pop(...)
 99  |      L.pop([index]) -> item -- remove and return item at index (default last).
100  |      Raises IndexError if list is empty or index is out of range.
101  |  
102  |  remove(...)
103  |      L.remove(value) -> None -- remove first occurrence of value.
104  |      Raises ValueError if the value is not present.
105  |  
106  |  reverse(...)
107  |      L.reverse() -- reverse *IN PLACE*
108  |  
109  |  sort(...)
110  |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
111  |  
112  |  ----------------------------------------------------------------------
113  |  Data and other attributes defined here:
114  |  
115  |  __hash__ = None


list


元组(tuple)

元组的创建:

t=(1,2,3)  创建一个元组
t=tuple([1,2,3])将列表转换为一个元组

tuple类型常用功能剖析 :
tup=(1,2,3,'a')这就是一个元组
元组跟列表几乎是一样的
列表可以进行修改,元组不可以进行修改(不能进行增删改操作)
count()计算元素出现的次数
index()获取指定元素的索引位置

元组的嵌套




python 的data格式 python中的datatype_python

python 的data格式 python中的datatype_python_02

1 class list(object)
  2  |  list() -> new empty list
  3  |  list(iterable) -> new list initialized from iterable's items
  4  |  
  5  |  Methods defined here:
  6  |  
  7  |  __add__(self, value, /)
  8  |      Return self+value.
  9  |  
 10  |  __contains__(self, key, /)
 11  |      Return key in self.
 12  |  
 13  |  __delitem__(self, key, /)
 14  |      Delete self[key].
 15  |  
 16  |  __eq__(self, value, /)
 17  |      Return self==value.
 18  |  
 19  |  __ge__(self, value, /)
 20  |      Return self>=value.
 21  |  
 22  |  __getattribute__(self, name, /)
 23  |      Return getattr(self, name).
 24  |  
 25  |  __getitem__(...)
 26  |      x.__getitem__(y) <==> x[y]
 27  |  
 28  |  __gt__(self, value, /)
 29  |      Return self>value.
 30  |  
 31  |  __iadd__(self, value, /)
 32  |      Implement self+=value.
 33  |  
 34  |  __imul__(self, value, /)
 35  |      Implement self*=value.
 36  |  
 37  |  __init__(self, /, *args, **kwargs)
 38  |      Initialize self.  See help(type(self)) for accurate signature.
 39  |  
 40  |  __iter__(self, /)
 41  |      Implement iter(self).
 42  |  
 43  |  __le__(self, value, /)
 44  |      Return self<=value.
 45  |  
 46  |  __len__(self, /)
 47  |      Return len(self).
 48  |  
 49  |  __lt__(self, value, /)
 50  |      Return self<value.
 51  |  
 52  |  __mul__(self, value, /)
 53  |      Return self*value.n
 54  |  
 55  |  __ne__(self, value, /)
 56  |      Return self!=value.
 57  |  
 58  |  __new__(*args, **kwargs) from builtins.type
 59  |      Create and return a new object.  See help(type) for accurate signature.
 60  |  
 61  |  __repr__(self, /)
 62  |      Return repr(self).
 63  |  
 64  |  __reversed__(...)
 65  |      L.__reversed__() -- return a reverse iterator over the list
 66  |  
 67  |  __rmul__(self, value, /)
 68  |      Return self*value.
 69  |  
 70  |  __setitem__(self, key, value, /)
 71  |      Set self[key] to value.
 72  |  
 73  |  __sizeof__(...)
 74  |      L.__sizeof__() -- size of L in memory, in bytes
 75  |  
 76  |  append(...)
 77  |      L.append(object) -> None -- append object to end
 78  |  
 79  |  clear(...)
 80  |      L.clear() -> None -- remove all items from L
 81  |  
 82  |  copy(...)
 83  |      L.copy() -> list -- a shallow copy of L
 84  |  
 85  |  count(...)
 86  |      L.count(value) -> integer -- return number of occurrences of value
 87  |  
 88  |  extend(...)
 89  |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 90  |  
 91  |  index(...)
 92  |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 93  |      Raises ValueError if the value is not present.
 94  |  
 95  |  insert(...)
 96  |      L.insert(index, object) -- insert object before index
 97  |  
 98  |  pop(...)
 99  |      L.pop([index]) -> item -- remove and return item at index (default last).
100  |      Raises IndexError if list is empty or index is out of range.
101  |  
102  |  remove(...)
103  |      L.remove(value) -> None -- remove first occurrence of value.
104  |      Raises ValueError if the value is not present.
105  |  
106  |  reverse(...)
107  |      L.reverse() -- reverse *IN PLACE*
108  |  
109  |  sort(...)
110  |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
111  |  
112  |  ----------------------------------------------------------------------
113  |  Data and other attributes defined here:
114  |  
115  |  __hash__ = None


tuple


字典(dict)

字典的创建:

a={..........}

a=dict(k1=123,k2=345)

a=dict(可迭代对象),比如li = [1,2,3],dict(li),不可以,但是dict(enumerate(li))可以

列表元素的添加:

dic['k1']=123或者dic.update({'k1':123}),但是第一种方式更为简单

dict类型常用功能剖析:
user_info = {'sam':1,'Jim':2}这就是一个字典,大括号里面是键值对
索引:user_info['sam']
user_info.keys()获取所有的key
user_info.values()获取所有的value
user_info.items()获取所有的键值对
user_info.clear():清除所有内容
user_info.get(key):根据key获取值,如果key不存在,可以指定一个默认值user_info.get('sas','123'),不存在的键sas,值为123
通过索引也可以获取值,但是get在key不存在的时候返回None,而索引会报错,所以推荐用get
user_info.has_key()检查字典中指定的key是否存在,python2有这个函数python3没有这个函数,用in代替:key in user_info.keys()
user_info.update()批量更新

pop()
popitem()
del user_info(key)删除键值对
循环:默认只输出key
for i in user_info:这句与for i in user_info.keys():是等价的,因为for in in user_info默认是对键进行循环。
print(i)输出key
for k,v in user_info.items():
print(k)输出key
print(v)输出value




python 的data格式 python中的datatype_python

python 的data格式 python中的datatype_python_02

1 class dict(object)
  2  |  dict() -> new empty dictionary
  3  |  dict(mapping) -> new dictionary initialized from a mapping object's
  4  |      (key, value) pairs
  5  |  dict(iterable) -> new dictionary initialized as if via:
  6  |      d = {}
  7  |      for k, v in iterable:
  8  |          d[k] = v
  9  |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 10  |      in the keyword argument list.  For example:  dict(one=1, two=2)
 11  |  
 12  |  Methods defined here:
 13  |  
 14  |  __contains__(self, key, /)
 15  |      True if D has a key k, else False.
 16  |  
 17  |  __delitem__(self, key, /)
 18  |      Delete self[key].
 19  |  
 20  |  __eq__(self, value, /)
 21  |      Return self==value.
 22  |  
 23  |  __ge__(self, value, /)
 24  |      Return self>=value.
 25  |  
 26  |  __getattribute__(self, name, /)
 27  |      Return getattr(self, name).
 28  |  
 29  |  __getitem__(...)
 30  |      x.__getitem__(y) <==> x[y]
 31  |  
 32  |  __gt__(self, value, /)
 33  |      Return self>value.
 34  |  
 35  |  __init__(self, /, *args, **kwargs)
 36  |      Initialize self.  See help(type(self)) for accurate signature.
 37  |  
 38  |  __iter__(self, /)
 39  |      Implement iter(self).
 40  |  
 41  |  __le__(self, value, /)
 42  |      Return self<=value.
 43  |  
 44  |  __len__(self, /)
 45  |      Return len(self).
 46  |  
 47  |  __lt__(self, value, /)
 48  |      Return self<value.
 49  |  
 50  |  __ne__(self, value, /)
 51  |      Return self!=value.
 52  |  
 53  |  __new__(*args, **kwargs) from builtins.type
 54  |      Create and return a new object.  See help(type) for accurate signature.
 55  |  
 56  |  __repr__(self, /)
 57  |      Return repr(self).
 58  |  
 59  |  __setitem__(self, key, value, /)
 60  |      Set self[key] to value.
 61  |  
 62  |  __sizeof__(...)
 63  |      D.__sizeof__() -> size of D in memory, in bytes
 64  |  
 65  |  clear(...)
 66  |      D.clear() -> None.  Remove all items from D.
 67  |  
 68  |  copy(...)
 69  |      D.copy() -> a shallow copy of D
 70  |  
 71  |  fromkeys(iterable, value=None, /) from builtins.type
 72  |      Returns a new dict with keys from iterable and values equal to value.
 73  |  
 74  |  get(...)
 75  |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
 76  |  
 77  |  items(...)
 78  |      D.items() -> a set-like object providing a view on D's items
 79  |  
 80  |  keys(...)
 81  |      D.keys() -> a set-like object providing a view on D's keys
 82  |  
 83  |  pop(...)
 84  |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 85  |      If key is not found, d is returned if given, otherwise KeyError is raised
 86  |  
 87  |  popitem(...)
 88  |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
 89  |      2-tuple; but raise KeyError if D is empty.
 90  |  
 91  |  setdefault(...)
 92  |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
 93  |  
 94  |  update(...)
 95  |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 96  |      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 97  |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 98  |      In either case, this is followed by: for k in F:  D[k] = F[k]
 99  |  
100  |  values(...)
101  |      D.values() -> an object providing a view on D's values
102  |  
103  |  ----------------------------------------------------------------------
104  |  Data and other attributes defined here:
105  |  
106  |  __hash__ = None


dict


set    

set数据类型:不允许重复的无序集合,所以不能通过下标来取
创建:s = set()空集合,s= {1,2,3,4}
转换:s = set([1,2,3,3])把可迭代对象里面相同的元素都去掉

set的方法:
add() 添加一个元素
clear()将集合清空
difference() ret = se.difference(be),找se中存在,be中不存在的元素,并给新的集合
difference_update 找se中存在,be中不存在的元素,并给新的集合,更新自己
discard()移除指定元素,不存在不报错
remove()移除指定元素,不存在会报错
set1.intersection(set2)交集,并给一个新的集合
set1.intersection_update(set2)交集,并更新自己
set1.isdisjoint(set2),有交集False,没交集True
set1.issubset(set2) set1是不是set2的子序列
set1.issuperset(set2) set1是不是set2的父序列
pop()与remove区别,pop可以拿到返回值(也就是移除的那个元素),remove拿不到

 一般来说,字符串执行一个功能,会产生一个新的,原来的不变,列表、元组、字典执行一个功能,一般会自身发生变化

还有一点,在类的源码定义中,

              如果没有staticmethod,调用方式为:

                            对象.方法;

              如果有staticmethod,调用方式为:

                            类.方法