python基础 数据类型

python3类的方法

对于Python,一切事物都是对象,对象基于类创建。

一、python运算符

1、结果是值

  算数运算符:例:a=10+1

  赋值运算符:例:a=a+1

2、结果是布尔值

  比较运算:例:a=1>2

  逻辑运算:例:a=1>2 or 1==1

  成员运算:例:a='李' in '李维他‘

 二、数据类型

python主要的数据类型主要包括以下几种类型:

(1) 数字型 :int

(2) 字符串:str

(3) bool型:bool

(4) 列表:list

(5) 元组 :tuple

(6) 字典:dict

对象的所有功能都放在类里,例如:数字都放在int里,字符串都放在str里...

三、数字型(int)

数字运算符

+       加法运算                                                                                  
-        减法运算
*       乘法运算
/  除法运算
**  幂、次方 
//  取余

%  取整数、取商

1、定义

如:a = 1234

数字型的全部函数如下,每个数字都有全部功能:

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

例如:def center(self, width, fillchar=None

  其中,def代表定义一个函数;其中参数未写 ‘=‘号的表示定义,给出值;写’=‘号的,可不写,为默认值。

  如:v = test.center(20, "*”) # 设置宽度为20,并将test内容在20宽度内居中,其他位置用*填充(未写占位符时用空格填充)。*******1234********

2、常用的几个重要函数:

四、字符串(str)

字符串运算符

+       字符串连接(拼接)                                                                             a+b
*        重复输出字符串                                     abc*3
[]       通过索引获取字符串中字符                              a[1] 
[ : ]    截取字符串中的一部分,也成为切片                                               a[1:4] 
in      成员运算符 -判断a是否包含b                            b in a 
not in  成员运算符 - 判断a是否不包含c                c not in a 

1、定义

如:a = '123'、b='12ac'、c='abcd'

2、字符串的全部功能函数如下:

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

3、常见的几个重要函数

  1.  查看变量类型、转换
1 a = '1234'                # 定义字符串
2 print(type(a), a)         # 输出(查看)变量类型,并输出变量值
3 b = int(a)                # 讲字符串转化为数字(字符串必须全是数字才行)
4 print(type(b),b)

  2.  改变字符串的二进制表示位数后数是多少

num = '011'
v = int(num, base=8)  #将num转换为数字,且是8进制数,不设置base默认是10进制
print(v)

 

 

  3.  英文字母大小写转换

 

 

1 a = 'aedSJFwe123'
2 v = a.islower()     # 判断字符串中字母是否全是小写
3 v1 = a.lower()      # 将字符全部转换为小写,仅对 ASCII 编码的小写有效
4 v2 = a.casefold()   # 将字符串转换成小写,Unicode 编码中凡是有对应的小写形式的,都会转换。
5 print(v, v1, v2)
6 n = a.isupper()     # 判断字符串中字母是否全是大写
7 n1 = a.upper()      # 将字母全部转换为大写
8 n2 = a.swapcase()   # 将大小写反转。
9 print(n, n1, n2)

  4.  count(self, sub, start=None, end=None) #去字符串中寻找,子序列出现的次数。统计字符串中包含子串的个数。

1 test = 'alexAlex'
2 v = test.count('ex')
3 v1 = test.count('ex', 1, 6)  # 后面两位是查找字符的区间,大于等于1小于6(起始位为0)。
4 print(v, v1)
5 
6 结果为:
7 2 1

  5.  find() #从开始往后找,找到第一个,获取其位置

1 v3 = test.find('ex')        #找不到时,为错误,输出-1
2 v4 = test.find('ex',5,8)  #后两位是查找区间(也可说成切片)代表>=5,<8。

  6.  format(*args, *kwargs)  #格式化,将一个字符串中的占位符替换为指定的值。

    1、test = ’i am {name}, age {a}'

       v = test.format(name='xiaoming', a=19)  # 其中{name}中name为占位符的名字。

   结果为:v= i am alex, age 19

     2、test = ’i am {1}, age {2}'

        v = test.format('xiaoming', 19, 12, 13)  # 其中占位符{}中,若为数字,则是从0开始写,否则替换内容数量得大于占位符中的数字。替换时,替换的内容从0还是对应。

   结果为:v= i am 19, age 12

  7.  fomat_map(self, mapping)

    v=test.format_map({'name':'alex', 'a'=19})   #格式化,传入的值'name':'alex', 'a'=19,成对对应。

  8.  isalnum()   #判断字符串中是否只包含字符和数字

       v = test.isalnum()  # 返回值为true、false。

  9.  center ()、rjust()、ljust():根据显示的长度中间对齐左对齐右对齐,不足的部分根据指定内容填充,默认为空格。

  10.  expandtabs()  # 断句     

    test = 'username\temail\tpasswd\nLL\tqq.com\t123\n'  # \t制表符,断句;\n换行符。
    v = test.expandtabs(20)    #以20个字符断句,不够20,空格补够20位。
    print(v)    

    username            email               passwd
    LL                  qq.com              123

  11.  字符串内容判断

  test = 'ada女人二'    # 定义字符串
  v = test.isalpha() # 判断字符串是否只包含文字字符,字符串仅包含中文字符也合法
  v1 = test.isalnum() # 判断字符串是否只包含文字和数字字符,字符串仅包含中文字符合法。若字符串包含空格、下划线、~等非文字数字式字符,均返回False。
  v2 = test.isdecimal() # 是否只有:数字(10进制数字)。
  v3 = test.isdigit() # 是否只有:数字,包含特殊数字如小标题数字。
  v4 = test.isnumeric() # 是否只有:数字,更能识别中文数字二
  v5 = test.isidentifier() # 判断是否符合标识符:字母、数字、下划线,不能开头数字。
  v6 = test.isprintable() # 判断字符串是否是合法的标识符(文字、数字、下划线)字符串仅包含中文字符合法,实际上这里判断的是变量名是否合法。
  print(v, v1, v2, v3, v4, v5, v6)
  结果是:True True False False False True True
  v7 = test.isupper()       # 字母是否都是大写
  v8 = test.islower() # 字母是否都是小写
  v9 = test.istitle() # 是否是标题,即每个单词首字母大写
  v10 = test.isspace() # 字符串是否都为空格,空格和没内容不一样
  print(v7, v8, v9, v10)   

  12.  swapcase()  #将字母大小写反转

  13.  title()  #将字符串转换为标题形式,即买个单词首字母大写,其余小写

  title():字符串中每个单词的首字母大写,其余小写。单词的首字符为非字母字符也不影响转换。字符串仅包含非字母字符合法,但返回原字符串。如:
  'ab cd'.title() -->'Ab Cd'   #字符串中每个单词的首字母大写
  '中国ab 123cd'.title() -->'中国Ab 123Cd'   #即使首字符为非字母字符,也可以进行转换
  '中国 123'.title() -->'中国 123'

  capitalize():字符串首字母大写,其余小写。如果字符串首字符为非字母字符,将返回原字符串。字符串仅包含非字母字符合法,但返回原字符串。如:
  'ab cd'.capitalize() -->'Ab cd'   #只转换字符串的首字母
  '中国ab 123cd'.capitalize() -->'中国ab 123cd'   #首字符为非字母字符,返回原字符串
  '中国 123'.capitalize() -->'中国 123'   #不会报错,返回原字符串

  14.  join()  #将字符串中的每个元素按指定分隔符进行连接

  test = '好好学习天天向上'
  t = '*'
  v = t.join(test) # 或者v= '*'.join(test)
  print(v)
结果是:好*好*学*习*天*天*向*上

  15.  lstrip(chars)  #chars参数是一个字符串,它包含了所有将要被移除的字符的集合,从左边(头)开始,遇到第一个非chars字符则停止。默认为空格。

    其中rstrip()、strip()分别从字符串的右边(尾)、两边开始匹配。

test = '123a2325dsjiu12342312312'
v = test.strip('123') #从原字符串的两边开始,匹配chars里包含的所有字符,直至遇到第一个非chars字符为止,原字符串中匹配到的所有字符都被移除。
print(v)
结果为:a2325dsjiu1234

  16. 总结:

    6个基本方法:join()、split()、find()、strip()、upper()、lower()

    4个常用方法:len()、for循环、索引、切片

   1、v = test[2]  # 索引下标,获取字符串中的某一个(或某范围)元素。

   2、 v = test[0:2]  # 切片取值为,第一个元素为0,第n个下标为n-1(最后一个,也可也写为-1,表示倒数第1个)。切片范围:第一个数表示为大于等于第0个,第二个为小于第2个。

           # v = test[0:-1]  #表示除了最后一个,其他都取。若想取尾,则不写就行,比如取全部为:test[0:]或test[:]

   3、v = len(test)  # 字符串共有几个字符组成。(Py3和py2不同) 

      len(li)   # 列表有几个元素组成,以列表中的‘,’为分隔符(li为列表)

   4、for in 循环

    for  变量名  in 字符串:

    test = '你还认识我吗'
    num = 0
    for v in test:
   print(v)
    或while num < len(test):
   v1 = test[num]
   num = num + 1
   print(v1)

    其中v 和v1结果是一样的,是两种方法。输出字符串的每个元素,每个元素为一行。

  17.  replace()  替换 

  test = '1232423112241234'
  v = test.maketrans('12', 'ab', '5')  # 对字符串test做映射表,即:把1映射到a,2映射到b,然后给translate()使用,做替换。第三个参数‘5’被映射成None,即为空,如果字符串中有5,则把所有5删除。最多有3个参数。
  v1 = test.translate(v)         # 利用maketrans做的映射,替换字符。
  v2 = test.replace('12', 'abc')    # 第一个是被替换的字符串,第二个是替换的,字符串可不等长
  v3 = test.replace('12', 'abc', 2)  # 第三个参数,表示替换掉几个,默认全部替换掉
  print(v, v1, v2, v3)
  结果为:{49: 97, 50: 98, 53: None} ab3b4b3aabb4ab34 abc324231abc24abc34 abc324231abc241234
v4 = test.translate(test.maketrans('12', 'ab', '5'))  # v4和v1的结果是一样的,一般都是连写。最多有3个参数。
maktrans 最多有3个参数。是一个静态方法,用于生成一个对照表,以供 translate 使用。
如果 maktrans 仅一个参数,则该参数必须是一个字典,字典的key要么是一个 Unicode 编码(一个整数),要么是一个长度为 1 的字符串,字典的 value 则可以是任意字符串、None或者 Unicode 编码。
如果 maktrans 有两个参数,则两个参数形成映射,且两个字符串必须是长度相等;
如果有第三个参数,则第三个参数也必须是字符串,该字符串将自动映射到 None:

   18.  分隔字符串  

    test=‘abcd123abcd123'

    1、partition('c')、rpartition()  # 结果为元组 (),不写参数时默认为空格。

    partition('c')  # 将以分隔符‘c’,把字符串分隔为三份,且从左边起遇到第一个c分隔,即(’ab'、'c'、‘123abcd')。rpartition()则是从右边开始查找。

    当查找不到字符时,则会在结尾处添加两个空字符。如partition('s'),则为(‘abcd123abcd123','','')

    2、split()  # 分隔符会被删除,第二个参数分隔几个字符,返回的是列表。如split('c',3)

     rsplit()  # 从右边开始。

     splitlines()  #以换行符为分隔,拆分一个包含多行的字符串,以每行为一个元素返回一个列表。如果字符串不是多行的,则返回整个字符串为列表的一个元素。

    3、startswith(self, prefix, start=None, end=None)   # 判断字符串是否以指定后缀开始,返回True或False。start和end指定判断的起始范围,默认全字符串。

     endswith(self, suffix, start=None, end=None)  # 判断字符串是否以指定后缀开始

 

 先整理到这,后续回继续整理。

关于python3的运算符可以参考这篇文章:https://www.cnblogs.com/aiwanbuhui/p/7903957.html

posted @ 2018-12-12 22:18  不巧是我  阅读(368)  评论(0)    收藏  举报