博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python基础数据型初探
阅读量:7158 次
发布时间:2019-06-29

本文共 35609 字,大约阅读时间需要 118 分钟。

总则

1 整体初识

(1)数字类型int:主要计算用;

(2)布尔值bool:主要判定用;

(3)字符串str:使用那可贼多了;

(4)列表list:可修改

(5)元组tuple:不可修改

(6)字典dict:很强大

(7)集合set:和中学时候的集合概念差不多

2 相互转换

(1)(2)(3)之间的转换;int转换为str  : str(int) str转换为int : int(str) 其中字符串组合只能是数字

int转换为bool : 0为feals,非零为true

bool转换为int  T=1  F=0

 

str转换为bool 非空字符串为1ture,空字符串为0false

bool转换为str  str(ture) str(false)

1 s="   "#非空2 print(bool(s))
str转换为bool例子

 

3 for循环

for i in msi:用户按照顺序循环可迭代对象;

4 def是python的函数,理解为模块也行

分则

(1)数字int类型

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 the12     given base.  The literal can be preceded by '+' or '-' and be surrounded13     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
int官方教学(英文原版)
1    def bit_length(self): # real signature unknown; restored from __doc__  2         """  3         int.bit_length() -> int  4           5         Number of bits necessary to represent self in binary.  6         >>> bin(37)  7         '0b100101'  8         >>> (37).bit_length()  9         6 10         """ 11         return 0 12  13     def conjugate(self, *args, **kwargs): # real signature unknown 14         """ Returns self, the complex conjugate of any int. """ 15         pass 16  17     @classmethod # known case 18     def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__  19         """ 20         int.from_bytes(bytes, byteorder, *, signed=False) -> int 21          22         Return the integer represented by the given array of bytes. 23          24         The bytes argument must be a bytes-like object (e.g. bytes or bytearray). 25          26         The byteorder argument determines the byte order used to represent the 27         integer.  If byteorder is 'big', the most significant byte is at the 28         beginning of the byte array.  If byteorder is 'little', the most 29         significant byte is at the end of the byte array.  To request the native 30         byte order of the host system, use `sys.byteorder' as the byte order value. 31          32         The signed keyword-only argument indicates whether two's complement is 33         used to represent the integer. 34         """ 35         pass 36  37     def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__  38         """ 39         int.to_bytes(length, byteorder, *, signed=False) -> bytes 40          41         Return an array of bytes representing an integer. 42          43         The integer is represented using length bytes.  An OverflowError is 44         raised if the integer is not representable with the given number of 45         bytes. 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 determines whether two's complement is 54         used to represent the integer.  If signed is False and a negative integer 55         is given, an OverflowError is raised. 56         """ 57         pass 58  59     def __abs__(self, *args, **kwargs): # real signature unknown 60         """ abs(self) """ 61         pass 62  63     def __add__(self, *args, **kwargs): # real signature unknown 64         """ Return self+value. """ 65         pass 66  67     def __and__(self, *args, **kwargs): # real signature unknown 68         """ Return self&value. """ 69         pass 70  71     def __bool__(self, *args, **kwargs): # real signature unknown 72         """ self != 0 """ 73         pass 74  75     def __ceil__(self, *args, **kwargs): # real signature unknown 76         """ Ceiling of an Integral returns itself. """ 77         pass 78  79     def __divmod__(self, *args, **kwargs): # real signature unknown 80         """ Return divmod(self, value). """ 81         pass 82  83     def __eq__(self, *args, **kwargs): # real signature unknown 84         """ Return self==value. """ 85         pass 86  87     def __float__(self, *args, **kwargs): # real signature unknown 88         """ float(self) """ 89         pass 90  91     def __floordiv__(self, *args, **kwargs): # real signature unknown 92         """ Return self//value. """ 93         pass 94  95     def __floor__(self, *args, **kwargs): # real signature unknown 96         """ Flooring an Integral returns itself. """ 97         pass 98  99     def __format__(self, *args, **kwargs): # real signature unknown100         pass101 102     def __getattribute__(self, *args, **kwargs): # real signature unknown103         """ Return getattr(self, name). """104         pass105 106     def __getnewargs__(self, *args, **kwargs): # real signature unknown107         pass108 109     def __ge__(self, *args, **kwargs): # real signature unknown110         """ Return self>=value. """111         pass112 113     def __gt__(self, *args, **kwargs): # real signature unknown114         """ Return self>value. """115         pass116 117     def __hash__(self, *args, **kwargs): # real signature unknown118         """ Return hash(self). """119         pass120 121     def __index__(self, *args, **kwargs): # real signature unknown122         """ Return self converted to an integer, if self is suitable for use as an index into a list. """123         pass124 125     def __init__(self, x, base=10): # known special case of int.__init__126         """127         int(x=0) -> integer128         int(x, base=10) -> integer129         130         Convert a number or string to an integer, or return 0 if no arguments131         are given.  If x is a number, return x.__int__().  For floating point132         numbers, this truncates towards zero.133         134         If x is not a number or if base is given, then x must be a string,135         bytes, or bytearray instance representing an integer literal in the136         given base.  The literal can be preceded by '+' or '-' and be surrounded137         by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.138         Base 0 means to interpret the base from the string as an integer literal.139         >>> int('0b100', base=0)140         4141         # (copied from class doc)142         """143         pass144 145     def __int__(self, *args, **kwargs): # real signature unknown146         """ int(self) """147         pass148 149     def __invert__(self, *args, **kwargs): # real signature unknown150         """ ~self """151         pass152 153     def __le__(self, *args, **kwargs): # real signature unknown154         """ Return self<=value. """155         pass156 157     def __lshift__(self, *args, **kwargs): # real signature unknown158         """ Return self<
>self. """247 pass248 249 def __rshift__(self, *args, **kwargs): # real signature unknown250 """ Return self>>value. """251 pass252 253 def __rsub__(self, *args, **kwargs): # real signature unknown254 """ Return value-self. """255 pass256 257 def __rtruediv__(self, *args, **kwargs): # real signature unknown258 """ Return value/self. """259 pass260 261 def __rxor__(self, *args, **kwargs): # real signature unknown262 """ Return value^self. """263 pass264 265 def __sizeof__(self, *args, **kwargs): # real signature unknown266 """ Returns size in memory, in bytes """267 pass268 269 def __str__(self, *args, **kwargs): # real signature unknown270 """ Return str(self). """271 pass272 273 def __sub__(self, *args, **kwargs): # real signature unknown274 """ Return self-value. """275 pass276 277 def __truediv__(self, *args, **kwargs): # real signature unknown278 """ Return self/value. """279 pass280 281 def __trunc__(self, *args, **kwargs): # real signature unknown282 """ Truncating an Integral returns itself. """283 pass284 285 def __xor__(self, *args, **kwargs): # real signature unknown286 """ Return self^value. """287 pass288 289 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default290 """the denominator of a rational number in lowest terms"""291 292 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default293 """the imaginary part of a complex number"""294 295 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default296 """the numerator of a rational number in lowest terms"""297 298 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default299 """the real part of a complex number"""
官方def
1 def bit_length(self): # real signature unknown; restored from __doc__ 2     """ 3     int.bit_length() -> int 4      5     Number of bits necessary to represent self in binary. 6     >>> bin(37) 7     '0b100101' 8     >>> (37).bit_length() 9     610     """11     return 012 13 def bit_length(self): #真实签名未知;恢复从__doc__14 ”“”15 int.bit_length()- > int16 用二进制表示自我所需的比特数。17 > > >bin(37)18 “0 b100101”19 > > >(37).bit_length()20 621 ”“”22 返回0
最常用的数字def中英对照

#bit_lenght() 当十进制用二进制表示时,最少使用的位数.

1 V=8 2 data=V.bit_length() 3 print(data) 4 输出值为4这是什么意思呢? 5 二进制就是等于2时就要进位。 6 0=00000000 7 1=00000001 8 2=00000010 9 3=0000001110 4=0000010011 5=0000010112 6=0000011013 7=0000011114 8=0000100015 9=0000100116 10=0000101017 ……18 就是8有四位就这个意思
例子以便理解

(2)布尔值bool

官方教程
1 class bool(int): 2     """ 3     bool(x) -> bool 4      5     Returns True when the argument x is true, False otherwise. 6     The builtins True and False are the only two instances of the class bool. 7     The class bool is a subclass of the class int, and cannot be subclassed. 8     """ 9     def __and__(self, *args, **kwargs): # real signature unknown10         """ Return self&value. """11         pass12 13     def __init__(self, x): # real signature unknown; restored from __doc__14         pass15 16     @staticmethod # known case of __new__17     def __new__(*args, **kwargs): # real signature unknown18         """ Create and return a new object.  See help(type) for accurate signature. """19         pass20 21     def __or__(self, *args, **kwargs): # real signature unknown22         """ Return self|value. """23         pass24 25     def __rand__(self, *args, **kwargs): # real signature unknown26         """ Return value&self. """27         pass28 29     def __repr__(self, *args, **kwargs): # real signature unknown30         """ Return repr(self). """31         pass32 33     def __ror__(self, *args, **kwargs): # real signature unknown34         """ Return value|self. """35         pass36 37     def __rxor__(self, *args, **kwargs): # real signature unknown38         """ Return value^self. """39         pass40 41     def __str__(self, *args, **kwargs): # real signature unknown42         """ Return str(self). """43         pass44 45     def __xor__(self, *args, **kwargs): # real signature unknown46         """ Return self^value. """47         pass
 

bool有两种值:true 1,false 0.就是反应条件正确与否.作为判断用

(3)字符串str

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         pass103 104     def format_map(self, mapping): # real signature unknown; restored from __doc__105         """106         S.format_map(mapping) -> str107         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]]) -> int116         117         Return the lowest index in S where substring sub is found, 118         such that sub is contained within S[start:end].  Optional119         arguments start and end are interpreted as in slice notation.120         121         Raises ValueError when the substring is not found.122         """123         return 0124 125     def isalnum(self): # real signature unknown; restored from __doc__126         """127         S.isalnum() -> bool128         129         Return True if all characters in S are alphanumeric130         and there is at least one character in S, False otherwise.131         """132         return False133 134     def isalpha(self): # real signature unknown; restored from __doc__135         """136         S.isalpha() -> bool137         138         Return True if all characters in S are alphabetic139         and there is at least one character in S, False otherwise.140         """141         return False142 143     def isdecimal(self): # real signature unknown; restored from __doc__144         """145         S.isdecimal() -> bool146         147         Return True if there are only decimal characters in S,148         False otherwise.149         """150         return False151 152     def isdigit(self): # real signature unknown; restored from __doc__153         """154         S.isdigit() -> bool155         156         Return True if all characters in S are digits157         and there is at least one character in S, False otherwise.158         """159         return False160 161     def isidentifier(self): # real signature unknown; restored from __doc__162         """163         S.isidentifier() -> bool164         165         Return True if S is a valid identifier according166         to the language definition.167         168         Use keyword.iskeyword() to test for reserved identifiers169         such as "def" and "class".170         """171         return False172 173     def islower(self): # real signature unknown; restored from __doc__174         """175         S.islower() -> bool176         177         Return True if all cased characters in S are lowercase and there is178         at least one cased character in S, False otherwise.179         """180         return False181 182     def isnumeric(self): # real signature unknown; restored from __doc__183         """184         S.isnumeric() -> bool185         186         Return True if there are only numeric characters in S,187         False otherwise.188         """189         return False190 191     def isprintable(self): # real signature unknown; restored from __doc__192         """193         S.isprintable() -> bool194         195         Return True if all characters in S are considered196         printable in repr() or S is empty, False otherwise.197         """198         return False199 200     def isspace(self): # real signature unknown; restored from __doc__201         """202         S.isspace() -> bool203         204         Return True if all characters in S are whitespace205         and there is at least one character in S, False otherwise.206         """207         return False208 209     def istitle(self): # real signature unknown; restored from __doc__210         """211         S.istitle() -> bool212         213         Return True if S is a titlecased string and there is at least one214         character in S, i.e. upper- and titlecase characters may only215         follow uncased characters and lowercase characters only cased ones.216         Return False otherwise.217         """218         return False219 220     def isupper(self): # real signature unknown; restored from __doc__221         """222         S.isupper() -> bool223         224         Return True if all cased characters in S are uppercase and there is225         at least one cased character in S, False otherwise.226         """227         return False228 229     def join(self, iterable): # real signature unknown; restored from __doc__230         """231         S.join(iterable) -> str232         233         Return a string which is the concatenation of the strings in the234         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]) -> str241         242         Return S left-justified in a Unicode string of length width. Padding is243         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() -> str250         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]) -> str258         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 unknown265         """266         Return a translation table usable for str.translate().267         268         If there is only one argument, it must be a dictionary mapping Unicode269         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, and272         in the resulting dictionary, each character in x will be mapped to the273         character at the same position in y. If there is a third argument, it274         must be a string, whose characters will be mapped to None in the result.275         """276         pass277 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 not284         found, return S and two empty strings.285         """286         pass287 288     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__289         """290         S.replace(old, new[, count]) -> str291         292         Return a copy of S with all occurrences of substring293         old replaced by new.  If the optional argument count is294         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]]) -> int301         302         Return the highest index in S where substring sub is found,303         such that sub is contained within S[start:end].  Optional304         arguments start and end are interpreted as in slice notation.305         306         Return -1 on failure.307         """308         return 0309 310     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__311         """312         S.rindex(sub[, start[, end]]) -> int313         314         Return the highest index in S where substring sub is found,315         such that sub is contained within S[start:end].  Optional316         arguments start and end are interpreted as in slice notation.317         318         Raises ValueError when the substring is not found.319         """320         return 0321 322     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__323         """324         S.rjust(width[, fillchar]) -> str325         326         Return S right-justified in a string of length width. Padding is327         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 return336         the part before it, the separator itself, and the part after it.  If the337         separator is not found, return two empty strings and S.338         """339         pass340 341     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__342         """343         S.rsplit(sep=None, maxsplit=-1) -> list of strings344         345         Return a list of the words in S, using sep as the346         delimiter string, starting at the end of the string and347         working to the front.  If maxsplit is given, at most maxsplit348         splits are done. If sep is not specified, any whitespace string349         is a separator.350         """351         return []352 353     def rstrip(self, chars=None): # real signature unknown; restored from __doc__354         """355         S.rstrip([chars]) -> str356         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 strings365         366         Return a list of the words in S, using sep as the367         delimiter string.  If maxsplit is given, at most maxsplit368         splits are done. If sep is not specified or is None, any369         whitespace string is a separator and empty strings are370         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 strings377         378         Return a list of the lines in S, breaking at line boundaries.379         Line breaks are not included in the resulting list unless keepends380         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]]) -> bool387         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 False394 395     def strip(self, chars=None): # real signature unknown; restored from __doc__396         """397         S.strip([chars]) -> str398         399         Return a copy of the string S with leading and trailing400         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() -> str408         409         Return a copy of S with uppercase characters converted to lowercase410         and vice versa.411         """412         return ""413 414     def title(self): # real signature unknown; restored from __doc__415         """416         S.title() -> str417         418         Return a titlecased version of S, i.e. words start with title case419         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) -> str426         427         Return a copy of the string S in which each character has been mapped428         through the given translation table. The table must implement429         lookup/indexing via __getitem__, for instance a dictionary or list,430         mapping Unicode ordinals to Unicode ordinals, strings, or None. If431         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() -> str439         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) -> str447         448         Pad a numeric string S with zeros on the left, to fill a field449         of the specified width. The string S is never truncated.450         """451         return ""452 453     def __add__(self, *args, **kwargs): # real signature unknown454         """ Return self+value. """455         pass456 457     def __contains__(self, *args, **kwargs): # real signature unknown458         """ Return key in self. """459         pass460 461     def __eq__(self, *args, **kwargs): # real signature unknown462         """ Return self==value. """463         pass464 465     def __format__(self, format_spec): # real signature unknown; restored from __doc__466         """467         S.__format__(format_spec) -> str468         469         Return a formatted version of S as described by format_spec.470         """471         return ""472 473     def __getattribute__(self, *args, **kwargs): # real signature unknown474         """ Return getattr(self, name). """475         pass476 477     def __getitem__(self, *args, **kwargs): # real signature unknown478         """ Return self[key]. """479         pass480 481     def __getnewargs__(self, *args, **kwargs): # real signature unknown482         pass483 484     def __ge__(self, *args, **kwargs): # real signature unknown485         """ Return self>=value. """486         pass487 488     def __gt__(self, *args, **kwargs): # real signature unknown489         """ Return self>value. """490         pass491 492     def __hash__(self, *args, **kwargs): # real signature unknown493         """ Return hash(self). """494         pass495 496     def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__497         """498         str(object='') -> str499         str(bytes_or_buffer[, encoding[, errors]]) -> str500         501         Create a new string object from the given object. If encoding or502         errors is specified, then the object must expose a data buffer503         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         pass511 512     def __iter__(self, *args, **kwargs): # real signature unknown513         """ Implement iter(self). """514         pass515 516     def __len__(self, *args, **kwargs): # real signature unknown517         """ Return len(self). """518         pass519 520     def __le__(self, *args, **kwargs): # real signature unknown521         """ Return self<=value. """522         pass523 524     def __lt__(self, *args, **kwargs): # real signature unknown525         """ Return self
size of S in memory, in bytes """559 pass560 561 def __str__(self, *args, **kwargs): # real signature unknown562 """ Return str(self). """563 pass
官方def

(1)name.capitalize() 首字母大写;

常用
s =  'alex wuSir'# *capitalize()首字母大写,其他字母小写# print(s.capitalize())# *swapcase()大小写反转# print(s.swapcase())# 非字母隔开的部分,首字母大写,其他小写#s =  'alex wuSir1taibai*ritian'# print(s.title())s =  'alexawuSir'# ***upper  全部大写# ***lower  全部小写# print(s.upper())# print(s.lower())# code = 'aeDd'# your_code = input('请输入验证码:')# if your_code.upper() == code.upper():#     print('输入正确')# else:print('请重新输入')# *以什么居中,填充物默认空# print(s.center(20))# print(s.center(20,'*'))

 

(2)name.swapcase()大小写翻转;

(3)name.title()           每单词的首行字母大写;

(3.1)name.upper() name.lower() 全部变为大;小写

(4)name.center(x,y) 居中以X为总长度,Y为填充物(没有则不填)

(5)name.count()       计算出字符串中元素出现的个数(可以切片)

# count 计算元素出现的次数# s =  'alexaaaaa wusir'# print(s.count('a'))# s = 'alex'# print(len(s))
count用法

 

(6)\t  

# s =  'al\tex wuSir'# print(s.expandtabs())
tab

 

(7)name.expandtabs()  默认将TAB变成八个空格,如果不足八则补全如果超过八则16.     

(8)name.startswitch      判断是否以....开头

#*** startswith  endswith# print(s.startswith('a'))# print(s.startswith('al'))# print(s.startswith('w',5))# print(s.startswith('W',5))# print('adfads\n','fdsa')# print(s)# s =  '\talex wusir\n'# s1 = 'alalelllllllxwusirbl'
startswith和end

 

(9)name.endswitch       判断是否以.....结尾

注:(8)(9)返回的都是bool值

(10)name.find();index   寻找字符串中元素是否存在.前者找不到返回-1,后者报错

# ***find()通过元素找索引,可以整体找,可以切片,找不到返回-1# index()通过元素找索引,可以整体找,可以切片,找不到会报错# print(s.find('a'),type(s.find('a')))# print(s.find('alex'),type(s.find('a')))# print(s.find('a'))# print(s.find('a',1,5))# print(s.find('L'))# print(s.index('L'))
find

 

(11)name.split()    以什么分割,最终形成一个列表不含有分割元素的新列表.

(12)X="{}{}{} ".format("eng",18,""mas)

X="{1}{0}{1}".format("eng",18,""mas)

X="{name}{age}{sex}".format(sex="gg",name="aa",age")

#************************format#第一种# s = '我叫{},今年{},身高{}'.format('金鑫',21,175)# print(s)#第二种# s = '我叫{0},今年{1},身高{2},我依然叫{0}'.format('金鑫',21,175)# print(s)#第三种# s = '我叫{name},今年{age},身高{high}'.format(name = '金鑫',high=175,age=21)# print(s)

 

(13)name.strip()         左右清除元素

#*****strip 去除字符串前后两端的空格,换行符,tab键等# print(s.strip())# print(s.lstrip())# print(s.rstrip())# print(s1.strip('lab'))# name = input('请输入名字:').strip()# if name == 'alex':#     print('somebody')# else:print('请重新输入')# s = 'alex;wusir;ritian'# s1 = 'alexalaria'
strip

 

#******split str --->list方法# print(s.split(';'))# print(s.split(';'))# print(s1.split('a',1))
View Code

 

(14)name.replace()    

#replace ******# s1 = '姐弟俩一起来老男孩老男孩老男孩'# s2 = s1.replace('老','小',1)# print(s2)# name='jinxin123'# print(name.isalnum()) #字符串由字母或数字组成# print(name.isalpha()) #字符串只由字母组成# print(name.isdigit()) #字符串只由数字组成
View Code

 

(15)is 系列 

name.isalnum()       字符串由字母或数字组成

name.isalpha()        字符串只由字母组成

name.isdigit()          字符串只由数字组成

                  

要讲解一下字符串的索引与切片

索引

概念:数据结构通过(对元素进行编号组织在一起的数据元素集合)这些元素可以是数字或者字符,甚至可以是其他数据结构.最基本的数据结构是序列(sequence).序列中每个元素被分配一个序号-----就是元素的位置,也成为索引.

性质:从左到右第一个索引是0,第二个则是1,以此类推.

        从右到左序列中最后一个元素序号为-1以此类推.

        序列也可以包含其他序列.

1 xingyao=["垚",18]2 weiheng=["魏",18]3 database=[xingyao,weiheng]4 print(database)5 6 结果为:7 [['邢垚', 18], ['魏恒', 18]]
序列实例

索引的所有元素都是编号的---从零开始递增,这些元素可以分别显示出来

实例
1 text="xingyao"2 print(text[1])3 4 5 输出结果是i6 因为序列从零开始所以[1]是第二个元素

切片

概念:通过索引(索引:索引:步长)截取字符串中的一段,形成新的字符串

性质:顾头不顾腚也可以表示为[ ) 头取大于等于,尾取小于.

1 a="lolhuiwoqingchunmadezhizhang"2 print(a[0:7])3 4 lolhuiw
切出一个区间
1 a="llohuiwoqingchunmadezhizhang"2 print(a[0:7:2])3 4 5 6 结果为louw
切出一个区间并且跳过元素序号
1 a="llohuiwoqingchunmadezhizhang"2 print(a[5:0:-1])3 4 结果为iuhol
有正反切割的字符创能够有正反

 元组:被称为只读列表,数据可以被查询,但不能修改,所以字符串的切片操作同样适用于元组.

迭代:概念是依次对序列中的每个元素重复执行某些操作.

转载于:https://www.cnblogs.com/cangshuchirou/p/8337035.html

你可能感兴趣的文章
PHP_014 错误和异常
查看>>
红黑树
查看>>
SuSE11安装MySQL5.6.40:编译安装方式、单实例
查看>>
CentOS6编译LAMP基于FPM模式的应用wordpress
查看>>
自定义TabBar
查看>>
c#设计模式-单例模式
查看>>
指针数组和数组指针
查看>>
win7升级nodejs8
查看>>
http断点续传
查看>>
悬浮显示input中所有的内容及css处理文字过长时显示为多余部分省略
查看>>
无线覆盖项目初步地勘——高校案例
查看>>
Hadoop MapReduce 处理2表join编程案例
查看>>
分布式存储-FastDFS
查看>>
iOS界面布局之三——纯代码的autoLayout及布局动画
查看>>
zabbix_server 3.0 安装
查看>>
Linux常用命令——find
查看>>
数据中台专栏(三):数据质量分析及提升
查看>>
iOS多点触控与手势识别
查看>>
Sql server--索引
查看>>
UML建模工具
查看>>