运算符
1、算数运算:
2、比较运算:
3、赋值运算:
4、逻辑运算:
5、成员运算:
基本数据类型
1、数字
int(整型)
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
1 # 数字 整形 int 2 # Python3里边 11111111111111111111111111111111 3 # Python2里边 11111111111111 4 # 长整形 long 5 # Python2里边 11111111111111111111111111111111
1 # 将字符串转换为数字 一个汉字在utf8里边3字节 2 a = "123" 3 print(type(a), a) 4 b = int(a) 5 print(type(b), b) 6 7 num = "0011" 8 v = int(num, base=16) 9 print(v) 10 11 age = 3 12 print(age.bit_length())
额外一大堆的方法看源码大海
class int(object): """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) """ def bit_length(self): """ 返回表示该数字的时占用的最少位数 """ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ 返回该复数的共轭复数 """ """ Returns self, the complex conjugate of any int. """ pass def __abs__(self): """ 返回绝对值 """ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __and__(self, y): """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): """ 比较两个数大小 """ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): """ 强制生成一个元组 """ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): """ 相除,得到商和余数组成的元组 """ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): """ x.__div__(y) <==> x/y """ pass def __float__(self): """ 转换为浮点类型 """ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown """ 内部调用 __new__方法或创建对象时传入参数使用 """ pass def __hash__(self): """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" """ x.__hash__() <==> hash(x) """ pass def __hex__(self): """ 返回当前数的 十六进制 表示 """ """ x.__hex__() <==> hex(x) """ pass def __index__(self): """ 用于切片,数字无意义 """ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x, base=10): # known special case of int.__init__ """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) # (copied from class doc) """ pass def __int__(self): """ 转换为整数 """ """ x.__int__() <==> int(x) """ pass def __invert__(self): """ x.__invert__() <==> ~x """ pass def __long__(self): """ 转换为长整数 """ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): """ x.__mul__(y) <==> x*y """ pass def __neg__(self): """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): """ 返回改值的 八进制 表示 """ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): """ x.__or__(y) <==> x|y """ pass def __pos__(self): """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): """ 幂,次方 """ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): """转化为解释器可读取的形式 """ """ x.__repr__() <==> repr(x) """ pass def __str__(self): """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" """ x.__str__() <==> str(x) """ pass def __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): """ x.__rxor__(y) <==> y^x """ pass def __sub__(self, y): """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): """ 返回数值被截取为整形的值,在整形中无意义 """ pass def __xor__(self, y): """ x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分母 = 1 """ """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 虚数,无意义 """ """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分子 = 数字大小 """ """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 实属,无意义 """ """the real part of a complex number""" int
2、布尔值
真或假
1或0
1 user = 'Eric' 2 pwd = '123' 3 v = user == 'Eric' and pwd == '123' or 1 == 1 and pwd == '99854' 4 print(v) # True 5 # 规则从左到右依次判断
注意:如果有括号,优先执行括号里边的内容
3、字符串
"hello world"
字符串常用功能:
- 移除空白
- 分割
- 长度
- 索引
- 切片
1 # test = 'ereic' 2 # test_over = '中国大' 3 # 索引 下标 获取字符串中的某个字符 4 # v = test[3] 5 # print(v) 6 7 # 切片 8 # v = test[0:-1] 9 # 0<= <-1取不到最后一个 10 # print(v) 11 12 # len长度 若汉字的话python2中拿到的是9 python3中就是3了 13 # print(len(test)) 14 # print(len(test_over)) 15 16 # join拼接 17 # print('_'.join(test_over)) 18 # replace替换 find rfind 19 # print(test.replace('e', 'a', 1)) 20 21 # 循环拿出每一个字符 22 # index = 0 23 # while index < len(test_over): 24 # v = test_over[index] 25 # print(v) 26 # index += 1 27 # print('======结束======') 28 # 29 # for item in test_over: 30 # print(item) 31 # 32 # for i in range(len(test_over)): 33 # print(test_over[i]) 34 # 字符串一旦创建,就不可以修改 35 # 一旦修改或者拼接,都会造成从新生成字符串(重新开辟新的内存空间) 36 # name = 'eric' 37 # age = '18' 38 # info = name + age 39 # print(info) 40 # 反转 41 # print(name[::-1]) 42 # range 在python3中这样不得立马创建 在python2中就立马直接就是0-99的列表创建了 43 # 这是一个优化机制 只有在循环遍历的时候才去创建,这样就内存占用率就小了 44 # 垃圾回收机制:自动清理如果没人用就清理了,这样内存占用率就小了 45 # range作用:创建生成连续的数字 46 # v = range(100) 47 # k = range(0, 100, 5) 48 # for i in v: 49 # print(i) 50 # for i in k: 51 # print(i) 52 # 结果range(0, 100)
1 name = "我爱中国" 2 # "我爱中国" 字符串 3 # "我" 代表字符串有且只有一个字符 4 # "我爱中国" 中国 子序列 5 if "爱中" in name: 6 # in not in 判断某个东西是否在某个东西里边 7 print('ok') 8 else: 9 print('Error')
1 user = 'Eric' 2 pwd = '123' 3 v = user == 'Eric' and pwd == '123' or 1 == 1 and pwd == '99854' 4 print(v) # True 5 # 规则从左到右依次判断 6 # 数字 7 # num = 123 8 # print(num.bit_length()) 9 10 # 字符串 str 11 # name = 'Eric' 12 # print(name.upper()) 13 # 数字 整形 int 14 # Python3里边 11111111111111111111111111111111 15 # Python2里边 11111111111111 16 # 长整形 long 17 # Python2里边 11111111111111111111111111111111 18 # 整型 int 19 # 将字符串转换为数字 一个汉字在utf8里边3字节 20 a = "123" 21 print(type(a), a) 22 b = int(a) 23 print(type(b), b) 24 num = "0011" 25 v = int(num, base=16) 26 print(v) 27 age = 3 28 print(age.bit_length()) 29 name = 'eRiceric' 30 # 首字母变大写 之后都小写 Eric 31 print(name.capitalize()) 32 # 全变小写 casefold()更牛逼些 很多未知对应可变小写 33 print(name.casefold()) 34 print(name.lower()) 35 # 设置宽度20并且内容居中布局空余位置用*填充 36 print(name.center(20, '*')) 37 print(name.center(20, '中')) 38 print(name.rjust(20, '中')) 39 print(name.ljust(20, '中')) 40 print(name.zfill(20)) 只能以0000000填充 41 42 # 计算当前个数 43 print(name.count('e', 3, 5)) 44 # 以什么结尾、开始 45 print(name.endswith('c')) 46 print(name.startswith('e')) 47 # 制表符 以制表符进行分割agshjskf indfkvj0824gdsh dsajskdj 48 s = 'agshjskf indfkvj0824gdsh dsajskdj' 49 print(s.expandtabs(6)) 50 # find从开始往后找,找到获取其位置 index找不到直接报错ValueError: substring not found 51 print(name.find('er', 0, 6)) 52 print(name.index('er', 0, 6)) 53 # 格式化 54 test = "you are {name},age {a}" 55 test = "you are {0},age {1}" 56 v = test.format(name='eric', a=18) 57 v = test.format('eric', 18) 58 print(v) 59 test = "you are {name},age {a}" 60 v = test.format_map({'name': 'eric', 'a': 18}) 61 print(v) 62 # 判断字符串是否只包含数字和字母 63 print(name.isalnum()) 64 # 判断是否是字母 isalpha 65 print(name.isalpha()) 66 67 # 判断是否是数字isdecimal普通点 不支持中文 isdigit不支持中文 isnumeric支持中文 小数都不行哈 68 # name = "③" 69 # name = "二" 70 name = "21.5" 71 print(name.isdecimal()) 72 print(name.isdigit()) 73 print(name.isnumeric()) 74 # isidentifier 字母 数字 下划线称标识符 75 a = '_123' 76 print(a.isidentifier()) 77 # 是否存在不可显示的字符换行制表符 isprintable 78 test = "adn aaa" 79 print(test.isprintable()) 80 # 判断空字符串 81 test = "" 82 test = " " 83 print(test.isspace()) 84 85 86 # 判断是否是标题 英文 87 test = "i love china" 88 print(test.title()) 89 print(test.istitle()) 90 ######################################### 91 # 将字符串中的每一个元素按照指定分隔符进行拼接 就是循环 92 a = '你是风儿我是沙' 93 s = ' ' 94 v = s.join(a) 95 k = '_'.join(a) 96 print(v, k) 97 # 判断是否是大小写 和 转换为大小写 98 test = "Eric" 99 print(test.islower()) 100 print(test.lower()) 101 print(test.isupper()) 102 print(test.upper()) 103 ######################################### 104 # 去除空格 还可以去除指定的字符 匹配子序列有点像正则都可以 105 test = "xaeric " 106 print(test.lstrip('xaahkksdh')) 107 print(test.rstrip()) 108 print(test.strip()) 109 110 # 对字符串进行分割 总的来说split用的多些 但是它拿不到被分割的字符 111 test = "testakdskjkj" 112 print(test.partition('s')) 113 print(test.rpartition('s')) 114 print(test.split('s', 2)) 115 print(test.rsplit('s', 2)) 116 # 结果 117 # ('te', 's', 'takdskjkj') 118 # ('testakd', 's', 'kjkj') 119 # ['te', 'takd', 'kjkj'] 120 # ['te', 'takd', 'kjkj'] 121 122 test = 'back' 123 print(test.startswith('b')) 124 print(test.endswith('k'))
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 首字母变大写 17 name = "nick is good, Today is nice day." 18 a = name.capitalize() 19 print(a) 20 """ 21 S.capitalize() -> str 22 23 Return a capitalized version of S, i.e. make the first character 24 have upper case and the rest lower case. 25 """ 26 return "" 27 28 def casefold(self): # real signature unknown; restored from __doc__ 29 """ 30 首字母变小写 31 name = "Nick is good, Today is nice day. 32 a =name.casefold() 33 print(a) 34 """ 35 S.casefold() -> str 36 37 Return a version of S suitable for caseless comparisons. 38 """ 39 return "" 40 41 def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ 42 """ 43 内容居中,width:总长度;fillchar:空白处填充内容,默认无。 44 name = "Nick is good, Today is nice day. 45 a = name.center(60,'$') 46 print(a) 47 """ 48 S.center(width[, fillchar]) -> str 49 Return S centered in a string of length width. Padding is 50 done using the specified fill character (default is a space) 51 """ 52 return "" 53 54 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 55 """ 56 子序列个数,0到26中n出现了几次。 57 name = "nck is good, Today is nice day. 58 a = name.count("n",0,26) 59 print(a) 60 """ 61 S.count(sub[, start[, end]]) -> int 62 63 Return the number of non-overlapping occurrences of substring sub in 64 string S[start:end]. Optional arguments start and end are 65 interpreted as in slice notation. 66 """ 67 return 0 68 69 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ 70 """ 71 """ 72 编码,针对unicode. 73 temp = "烧饼 74 temp.encode("unicode") 75 """ 76 S.encode(encoding='utf-8', errors='strict') -> bytes 77 78 Encode S using the codec registered for encoding. Default encoding 79 is 'utf-8'. errors may be given to set a different error 80 handling scheme. Default is 'strict' meaning that encoding errors raise 81 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 82 'xmlcharrefreplace' as well as any other name registered with 83 codecs.register_error that can handle UnicodeEncodeErrors. 84 """ 85 return b"" 86 87 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ 88 """ 89 """ 90 是否以XX结束,0到4是否以k结尾 91 name = "nck is good, Today is nice day. 92 a = name.endswith("k",0,4) 93 print(a) 94 """ 95 S.endswith(suffix[, start[, end]]) -> bool 96 97 Return True if S ends with the specified suffix, False otherwise. 98 With optional start, test S beginning at that position. 99 With optional end, stop comparing S at that position. 100 suffix can also be a tuple of strings to try. 101 """ 102 return False 103 104 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ 105 """ 106 """ 107 将tab转换成空格,默认一个tab转换成8个空格 108 a = n.expandtabs() 109 b = n.expandtabs(16) 110 print(a) 111 print(b) 112 """ 113 S.expandtabs(tabsize=8) -> str 114 115 Return a copy of S where all tab characters are expanded using spaces. 116 If tabsize is not given, a tab size of 8 characters is assumed. 117 """ 118 return "" 119 120 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 121 """ 122 """ 123 寻找子序列位置,如果没找到,返回 -1。 124 name = "nck is good, Today is nice day. " 125 a = name.find("nickk") 126 print(a) 127 """ 128 S.find(sub[, start[, end]]) -> int 129 130 Return the lowest index in S where substring sub is found, 131 such that sub is contained within S[start:end]. Optional 132 arguments start and end are interpreted as in slice notation. 133 134 Return -1 on failure. 135 """ 136 return 0 137 138 def format(self, *args, **kwargs): # known special case of str.format 139 """ 140 """ 141 字符串格式化,动态参数 142 name = "nck is good, Today is nice day. " 143 a = name.format() 144 print(a) 145 """ 146 S.format(*args, **kwargs) -> str 147 148 Return a formatted version of S, using substitutions from args and kwargs. 149 The substitutions are identified by braces ('{' and '}'). 150 """ 151 pass 152 153 def format_map(self, mapping): # real signature unknown; restored from __doc__ 154 """ 155 """ 156 dict = {'Foo': 54.23345} 157 fmt = "Foo = {Foo:.3f}" 158 result = fmt.format_map(dict) 159 print(result) #Foo = 54.233 160 """ 161 S.format_map(mapping) -> str 162 163 Return a formatted version of S, using substitutions from mapping. 164 The substitutions are identified by braces ('{' and '}'). 165 """ 166 return "" 167 168 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 169 """ 170 """ 171 #子序列位置,如果没有找到就报错 172 name = "nck is good, Today is nice day. " 173 a = name.index("nick") 174 print(a) 175 """ 176 S.index(sub[, start[, end]]) -> int 177 178 Like S.find() but raise ValueError when the substring is not found. 179 """ 180 return 0 181 182 def isalnum(self): # real signature unknown; restored from __doc__ 183 """ 184 """ 185 是否是字母和数字 186 name = "nck is good, Today is nice day. " 187 a = name.isalnum() 188 print(a) 189 """ 190 S.isalnum() -> bool 191 192 Return True if all characters in S are alphanumeric 193 and there is at least one character in S, False otherwise. 194 """ 195 return False 196 197 def isalpha(self): # real signature unknown; restored from __doc__ 198 """ 199 """ 200 是否是字母 201 name = "nck is good, Today is nice day. " 202 a = name.isalpha() 203 print(a) 204 """ 205 S.isalpha() -> bool 206 207 Return True if all characters in S are alphabetic 208 and there is at least one character in S, False otherwise. 209 """ 210 return False 211 212 def isdecimal(self): # real signature unknown; restored from __doc__ 213 """ 214 检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。 215 """ 216 S.isdecimal() -> bool 217 218 Return True if there are only decimal characters in S, 219 False otherwise. 220 """ 221 return False 222 223 def isdigit(self): # real signature unknown; restored from __doc__ 224 """ 225 """ 226 是否是数字 227 name = "nck is good, Today is nice day. " 228 a = name.isdigit() 229 print(a) 230 """ 231 S.isdigit() -> bool 232 233 Return True if all characters in S are digits 234 and there is at least one character in S, False otherwise. 235 """ 236 return False 237 238 def isidentifier(self): # real signature unknown; restored from __doc__ 239 """ 240 """ 241 判断字符串是否可为合法的标识符 242 """ 243 S.isidentifier() -> bool 244 245 Return True if S is a valid identifier according 246 to the language definition. 247 248 Use keyword.iskeyword() to test for reserved identifiers 249 such as "def" and "class". 250 """ 251 return False 252 253 def islower(self): # real signature unknown; restored from __doc__ 254 """ 255 """ 256 是否小写 257 name = "nck is good, Today is nice day. " 258 a = name.islower() 259 print(a) 260 """ 261 S.islower() -> bool 262 263 Return True if all cased characters in S are lowercase and there is 264 at least one cased character in S, False otherwise. 265 """ 266 return False 267 268 def isnumeric(self): # real signature unknown; restored from __doc__ 269 """ 270 """ 271 检查是否只有数字字符组成的字符串 272 name = "111111111111111” 273 a = name.isnumeric() 274 print(a) 275 """ 276 S.isnumeric() -> bool 277 278 Return True if there are only numeric characters in S, 279 False otherwise. 280 """ 281 return False 282 283 def isprintable(self): # real signature unknown; restored from __doc__ 284 """ 285 """ 286 判断字符串中所有字符是否都属于可见字符 287 name = "nck is good, Today is nice day. " 288 a = name.isprintable() 289 print(a) 290 """ 291 S.isprintable() -> bool 292 293 Return True if all characters in S are considered 294 printable in repr() or S is empty, False otherwise. 295 """ 296 return False 297 298 def isspace(self): # real signature unknown; restored from __doc__ 299 """ 300 """ 301 字符串是否只由空格组成 302 name = " " 303 a = name.isspace() 304 print(a) 305 """ 306 S.isspace() -> bool 307 308 Return True if all characters in S are whitespace 309 and there is at least one character in S, False otherwise. 310 """ 311 return False 312 313 def istitle(self): # real signature unknown; restored from __doc__ 314 """ 315 """ 316 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写 317 name = "Nick, Today." 318 a = name.istitle() 319 print(a) 320 """ 321 """ 322 S.istitle() -> bool 323 324 Return True if S is a titlecased string and there is at least one 325 character in S, i.e. upper- and titlecase characters may only 326 follow uncased characters and lowercase characters only cased ones. 327 Return False otherwise. 328 """ 329 return False 330 331 def isupper(self): # real signature unknown; restored from __doc__ 332 """ 333 """ 334 检测字符串中所有的字母是否都为大写 335 name = "NICK" 336 a = name.isupper() 337 print(a) 338 """ 339 S.isupper() -> bool 340 341 Return True if all cased characters in S are uppercase and there is 342 at least one cased character in S, False otherwise. 343 """ 344 return False 345 346 def join(self, iterable): # real signature unknown; restored from __doc__ 347 """ 348 """ 349 连接两个字符串 350 li = ["nick","serven"] 351 a = "".join(li) 352 b = "_".join(li) 353 print(a) 354 print(b) 355 """ 356 S.join(iterable) -> str 357 358 Return a string which is the concatenation of the strings in the 359 iterable. The separator between elements is S. 360 """ 361 return "" 362 363 def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ 364 """ 365 """ 366 向左对齐,右侧填充 367 name = "nck is good, Today is nice day. " 368 a = name.ljust(66) 369 print(a) 370 """ 371 S.ljust(width[, fillchar]) -> str 372 373 Return S left-justified in a Unicode string of length width. Padding is 374 done using the specified fill character (default is a space). 375 """ 376 return "" 377 378 def lower(self): # real signature unknown; restored from __doc__ 379 """ 380 """ 381 容左对齐,右侧填充 382 name = "NiNi" 383 a = name.lower() 384 print(a) 385 """ 386 S.lower() -> str 387 388 Return a copy of the string S converted to lowercase. 389 """ 390 return "" 391 392 def lstrip(self, chars=None): # real signature unknown; restored from __doc__ 393 """ 394 """ 移除左侧空白 """ 395 S.lstrip([chars]) -> str 396 397 Return a copy of the string S with leading whitespace removed. 398 If chars is given and not None, remove characters in chars instead. 399 """ 400 return "" 401 402 def maketrans(self, *args, **kwargs): # real signature unknown 403 """ 404 """ 405 用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 406 from string import maketrans 407 intab = "aeiou" 408 outtab = "12345" 409 trantab = maketrans(intab, outtab) 410 str = "this is string example....wow!!!"; 411 print str.translate(trantab); 412 """ 413 Return a translation table usable for str.translate(). 414 415 If there is only one argument, it must be a dictionary mapping Unicode 416 ordinals (integers) or characters to Unicode ordinals, strings or None. 417 Character keys will be then converted to ordinals. 418 If there are two arguments, they must be strings of equal length, and 419 in the resulting dictionary, each character in x will be mapped to the 420 character at the same position in y. If there is a third argument, it 421 must be a string, whose characters will be mapped to None in the result. 422 """ 423 pass 424 425 def partition(self, sep): # real signature unknown; restored from __doc__ 426 """ 427 """ 428 分割,前,中,后三部分 429 name = "Nick is good, Today is nice day." 430 a = name.partition("good") 431 print(a) 432 """ 433 S.partition(sep) -> (head, sep, tail) 434 435 Search for the separator sep in S, and return the part before it, 436 the separator itself, and the part after it. If the separator is not 437 found, return S and two empty strings. 438 """ 439 pass 440 441 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ 442 """ 443 """ 444 替换 445 name = "Nick is good, Today is nice day." 446 a = name.replace("good","man") 447 print(a) 448 """ 449 S.replace(old, new[, count]) -> str 450 451 Return a copy of S with all occurrences of substring 452 old replaced by new. If the optional argument count is 453 given, only the first count occurrences are replaced. 454 """ 455 return "" 456 457 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 458 """ 459 """ 460 返回字符串最后一次出现的位置,如果没有匹配项则返回-1 461 """ 462 S.rfind(sub[, start[, end]]) -> int 463 464 Return the highest index in S where substring sub is found, 465 such that sub is contained within S[start:end]. Optional 466 arguments start and end are interpreted as in slice notation. 467 468 Return -1 on failure. 469 """ 470 return 0 471 472 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 473 """ 474 """ 475 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常 476 """ 477 S.rindex(sub[, start[, end]]) -> int 478 479 Like S.rfind() but raise ValueError when the substring is not found. 480 """ 481 return 0 482 483 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ 484 """ 485 """ 486 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串 487 str = "this is string example....wow!!!" 488 print(str.rjust(50, '$')) 489 """ 490 S.rjust(width[, fillchar]) -> str 491 492 Return S right-justified in a string of length width. Padding is 493 done using the specified fill character (default is a space). 494 """ 495 return "" 496 497 def rpartition(self, sep): # real signature unknown; restored from __doc__ 498 """ 499 """ 500 根据指定的分隔符将字符串进行分割 501 """ 502 S.rpartition(sep) -> (head, sep, tail) 503 504 Search for the separator sep in S, starting at the end of S, and return 505 the part before it, the separator itself, and the part after it. If the 506 separator is not found, return two empty strings and S. 507 """ 508 pass 509 510 def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 511 """ 512 """ 513 指定分隔符对字符串进行切片 514 name = "Nick is good, Today is nice day." 515 a = name.rsplit("is") 516 print(a) 517 """ 518 S.rsplit(sep=None, maxsplit=-1) -> list of strings 519 520 Return a list of the words in S, using sep as the 521 delimiter string, starting at the end of the string and 522 working to the front. If maxsplit is given, at most maxsplit 523 splits are done. If sep is not specified, any whitespace string 524 is a separator. 525 """ 526 return [] 527 528 def rstrip(self, chars=None): # real signature unknown; restored from __doc__ 529 """ 530 """ 531 删除 string 字符串末尾的指定字符(默认为空格) 532 """ 533 S.rstrip([chars]) -> str 534 535 Return a copy of the string S with trailing whitespace removed. 536 If chars is given and not None, remove characters in chars instead. 537 """ 538 return "" 539 540 def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 541 """ 542 """ 543 通过指定分隔符对字符串进行切片 544 str = "Line1-abcdef Line2-abc Line4-abcd"; 545 print str.split( ); 546 print str.split(' ', 1 ); 547 """ 548 S.split(sep=None, maxsplit=-1) -> list of strings 549 550 Return a list of the words in S, using sep as the 551 delimiter string. If maxsplit is given, at most maxsplit 552 splits are done. If sep is not specified or is None, any 553 whitespace string is a separator and empty strings are 554 removed from the result. 555 """ 556 return [] 557 558 def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ 559 """ 560 """ 561 按照行分隔,返回一个包含各行作为元素的列表 562 """ 563 S.splitlines([keepends]) -> list of strings 564 565 Return a list of the lines in S, breaking at line boundaries. 566 Line breaks are not included in the resulting list unless keepends 567 is given and true. 568 """ 569 return [] 570 571 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ 572 """ 573 """ 574 检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False 575 """ 576 S.startswith(prefix[, start[, end]]) -> bool 577 578 Return True if S starts with the specified prefix, False otherwise. 579 With optional start, test S beginning at that position. 580 With optional end, stop comparing S at that position. 581 prefix can also be a tuple of strings to try. 582 """ 583 return False 584 585 def strip(self, chars=None): # real signature unknown; restored from __doc__ 586 """ 587 """ 588 用于移除字符串头尾指定的字符(默认为空格). 589 """ 590 S.strip([chars]) -> str 591 592 Return a copy of the string S with leading and trailing 593 whitespace removed. 594 If chars is given and not None, remove characters in chars instead. 595 """ 596 return "" 597 598 def swapcase(self): # real signature unknown; restored from __doc__ 599 """ 600 """ 601 用于对字符串的大小写字母进行转换 602 """ 603 S.swapcase() -> str 604 605 Return a copy of S with uppercase characters converted to lowercase 606 and vice versa. 607 """ 608 return "" 609 610 def title(self): # real signature unknown; restored from __doc__ 611 """ 612 S.title() -> str 613 614 Return a titlecased version of S, i.e. words start with title case 615 characters, all remaining cased characters have lower case. 616 """ 617 return "" 618 619 def translate(self, table): # real signature unknown; restored from __doc__ 620 """ 621 S.translate(table) -> str 622 623 Return a copy of the string S in which each character has been mapped 624 through the given translation table. The table must implement 625 lookup/indexing via __getitem__, for instance a dictionary or list, 626 mapping Unicode ordinals to Unicode ordinals, strings, or None. If 627 this operation raises LookupError, the character is left untouched. 628 Characters mapped to None are deleted. 629 """ 630 return "" 631 632 def upper(self): # real signature unknown; restored from __doc__ 633 """ 634 """ 635 将字符串中的小写字母转为大写字母 636 """ 637 S.upper() -> str 638 639 Return a copy of S converted to uppercase. 640 """ 641 return "" 642 643 def zfill(self, width): # real signature unknown; restored from __doc__ 644 """ 645 """ 646 返回指定长度的字符串,原字符串右对齐,前面填充0 647 """ 648 S.zfill(width) -> str 649 650 Pad a numeric string S with zeros on the left, to fill a field 651 of the specified width. The string S is never truncated. 652 """ 653 return "" 654 655 def __add__(self, *args, **kwargs): # real signature unknown 656 """ Return self+value. """ 657 pass 658 659 def __contains__(self, *args, **kwargs): # real signature unknown 660 """ Return key in self. """ 661 pass 662 663 def __eq__(self, *args, **kwargs): # real signature unknown 664 """ Return self==value. """ 665 pass 666 667 def __format__(self, format_spec): # real signature unknown; restored from __doc__ 668 """ 669 S.__format__(format_spec) -> str 670 671 Return a formatted version of S as described by format_spec. 672 """ 673 return "" 674 675 def __getattribute__(self, *args, **kwargs): # real signature unknown 676 """ Return getattr(self, name). """ 677 pass 678 679 def __getitem__(self, *args, **kwargs): # real signature unknown 680 """ Return self[key]. """ 681 pass 682 683 def __getnewargs__(self, *args, **kwargs): # real signature unknown 684 pass 685 686 def __ge__(self, *args, **kwargs): # real signature unknown 687 """ Return self>=value. """ 688 pass 689 690 def __gt__(self, *args, **kwargs): # real signature unknown 691 """ Return self>value. """ 692 pass 693 694 def __hash__(self, *args, **kwargs): # real signature unknown 695 """ Return hash(self). """ 696 pass 697 698 def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__ 699 """ 700 str(object='') -> str 701 str(bytes_or_buffer[, encoding[, errors]]) -> str 702 703 Create a new string object from the given object. If encoding or 704 errors is specified, then the object must expose a data buffer 705 that will be decoded using the given encoding and error handler. 706 Otherwise, returns the result of object.__str__() (if defined) 707 or repr(object). 708 encoding defaults to sys.getdefaultencoding(). 709 errors defaults to 'strict'. 710 # (copied from class doc) 711 """ 712 pass 713 714 def __iter__(self, *args, **kwargs): # real signature unknown 715 """ Implement iter(self). """ 716 pass 717 718 def __len__(self, *args, **kwargs): # real signature unknown 719 """ Return len(self). """ 720 pass 721 722 def __le__(self, *args, **kwargs): # real signature unknown 723 """ Return self<=value. """ 724 pass 725 726 def __lt__(self, *args, **kwargs): # real signature unknown 727 """ Return self<value. """ 728 pass 729 730 def __mod__(self, *args, **kwargs): # real signature unknown 731 """ Return self%value. """ 732 pass 733 734 def __mul__(self, *args, **kwargs): # real signature unknown 735 """ Return self*value.n """ 736 pass 737 738 @staticmethod # known case of __new__ 739 def __new__(*args, **kwargs): # real signature unknown 740 """ Create and return a new object. See help(type) for accurate signature. """ 741 pass 742 743 def __ne__(self, *args, **kwargs): # real signature unknown 744 """ Return self!=value. """ 745 pass 746 747 def __repr__(self, *args, **kwargs): # real signature unknown 748 """ Return repr(self). """ 749 pass 750 751 def __rmod__(self, *args, **kwargs): # real signature unknown 752 """ Return value%self. """ 753 pass 754 755 def __rmul__(self, *args, **kwargs): # real signature unknown 756 """ Return self*value. """ 757 pass 758 759 def __sizeof__(self): # real signature unknown; restored from __doc__ 760 """ S.__sizeof__() -> size of S in memory, in bytes """ 761 pass 762 763 def __str__(self, *args, **kwargs): # real signature unknown 764 """ Return str(self). """ 765 pass
str源码的一些分析操作
4、列表
创建列表:
1 name_list = ['玛莎拉蒂', '扫地僧人', 'eric'] 2 或者 3 name_list = list(['玛莎拉蒂', '扫地僧人', 'eric'])
基本操作:
- 索引
- 切片
- 追加
- 删除
- 长度
- 循环
- 包含
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 # 1.列表 list 5 # 创建列表 通过list类创建对象li 6 # li = [1, 12, 9, 'age', ['藏獒', 'pang'], 'eric', True] 7 # 中括号括起来 8 # ,逗号分隔 9 # 列表中的元素可以是数字 字符串 列表 布尔值 基本所有的都能放进去 10 # "集合" 内部放东西 11 12 # 2.索引取值 13 # print(li[2]) 14 # 切片结果仍然是列表 15 # print(li[2:-3]) 16 # for循环 while循环 17 # for i in li: 18 # print(i) 19 20 # 3.修改 21 # li[1] = 20 22 # li[1] = [11, 22, 33] 23 # li[1:3] = [120, 90] 24 # print(li) 25 26 # 4.删除 27 # del li[1] 28 # del li[1:3] 29 # print(li) 30 31 # 5.也支持in操作 在列表中的元素这里是以逗号分隔 32 # 这样肯定输出False 33 # v = '藏獒' in li 34 # print(v) 35 36 # 6.一层层的找下去 37 # li = [1, 12, 9, 'age', ['藏獒', 'pang', [1, 22, 9]], 'eric', True] 38 # v = li[4][2][1] 39 # print(v) 40 41 # 7.字符串转换成列表 42 # s = 'asjhd' 43 # new_li = list(s) 44 # print(new_li) 45 46 # 8.列表转字符串 数字+字符串(需要转换下) 字符串(join) 47 # li = [11, 22, 33, '123', 'eric'] 48 # s = '' 49 # for i in li: 50 # s = s + str(i) 51 # print(s) 52 # li = ['123', 'eric'] 53 # print(''.join(li)) 54 55 # 9.追加 原来基础上追加数字 字符串 列表都行 56 # li = [11, 22, 33, 44] 57 # li.append(5) 58 # print(li) 59 60 # 10.清空 61 # li.clear() 62 # print(li) 63 64 # 11.拷贝 浅拷贝 65 # v = li.copy() 66 # print(v) 67 68 # 12.计算元素出现的次数 69 # v = li.count(11) 70 # print(v) 71 72 # 13.扩展原来的列表 73 # li.extend([98, '不得了']) # 参数必须是可迭代对象,内部要进行循环 74 # print(li) 75 76 # 14.根据值获取当前值索引 左边优先 一旦找到就不会向下找了 77 # li = [11, 22, 33, 22, 44, 55] 78 # v = li.index(22, 2, 5) 79 # print(v) 80 81 #15.在指定位置插入元素 82 # li = [11, 22, 33, 22, 44, 55] 83 # li.insert(0, 99) 84 # print(li) 85 86 # 16.pop默认删除某个值,并获取当前值,没指定索引默认从最后一个删除 87 # li = [11, 22, 33, 22, 44, 55] 88 # v = li.pop(1) 89 # print(v) 90 # print(li) 91 92 # 17.删除列表指定值 左边优先 93 # li = [11, 22, 33, 22, 44, 55] 94 # li.remove(22) 95 # v = li.remove(22) 打印为None 因为是原来的列表嘛 96 # print(li) 97 # 18.反转 98 # li = [11, 22, 33, 22, 44, 55] 99 # li.reverse() 100 # print(li) 101 102 # 19.排序 103 # li = [11, 22, 33, 22, 44, 55] 104 # li.sort() 从小到大 105 # li.sort(reverse=True) 从大到小 106 # print(li)
列表在内存中存储过程(链表):
list源码分析:
1 class list(object): 2 """ 3 list() -> new empty list 4 list(iterable) -> new list initialized from iterable's items 5 """ 6 def append(self, p_object): # real signature unknown; restored from __doc__ 7 """ L.append(object) -- append object to end """ 8 pass 9 10 def count(self, value): # real signature unknown; restored from __doc__ 11 """ L.count(value) -> integer -- return number of occurrences of value """ 12 return 0 13 14 def extend(self, iterable): # real signature unknown; restored from __doc__ 15 """ L.extend(iterable) -- extend list by appending elements from the iterable """ 16 pass 17 18 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 19 """ 20 L.index(value, [start, [stop]]) -> integer -- return first index of value. 21 Raises ValueError if the value is not present. 22 """ 23 return 0 24 25 def insert(self, index, p_object): # real signature unknown; restored from __doc__ 26 """ L.insert(index, object) -- insert object before index """ 27 pass 28 29 def pop(self, index=None): # real signature unknown; restored from __doc__ 30 """ 31 L.pop([index]) -> item -- remove and return item at index (default last). 32 Raises IndexError if list is empty or index is out of range. 33 """ 34 pass 35 36 def remove(self, value): # real signature unknown; restored from __doc__ 37 """ 38 L.remove(value) -- remove first occurrence of value. 39 Raises ValueError if the value is not present. 40 """ 41 pass 42 43 def reverse(self): # real signature unknown; restored from __doc__ 44 """ L.reverse() -- reverse *IN PLACE* """ 45 pass 46 47 def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ 48 """ 49 L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; 50 cmp(x, y) -> -1, 0, 1 51 """ 52 pass 53 54 def __add__(self, y): # real signature unknown; restored from __doc__ 55 """ x.__add__(y) <==> x+y """ 56 pass 57 58 def __contains__(self, y): # real signature unknown; restored from __doc__ 59 """ x.__contains__(y) <==> y in x """ 60 pass 61 62 def __delitem__(self, y): # real signature unknown; restored from __doc__ 63 """ x.__delitem__(y) <==> del x[y] """ 64 pass 65 66 def __delslice__(self, i, j): # real signature unknown; restored from __doc__ 67 """ 68 x.__delslice__(i, j) <==> del x[i:j] 69 70 Use of negative indices is not supported. 71 """ 72 pass 73 74 def __eq__(self, y): # real signature unknown; restored from __doc__ 75 """ x.__eq__(y) <==> x==y """ 76 pass 77 78 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 79 """ x.__getattribute__('name') <==> x.name """ 80 pass 81 82 def __getitem__(self, y): # real signature unknown; restored from __doc__ 83 """ x.__getitem__(y) <==> x[y] """ 84 pass 85 86 def __getslice__(self, i, j): # real signature unknown; restored from __doc__ 87 """ 88 x.__getslice__(i, j) <==> x[i:j] 89 90 Use of negative indices is not supported. 91 """ 92 pass 93 94 def __ge__(self, y): # real signature unknown; restored from __doc__ 95 """ x.__ge__(y) <==> x>=y """ 96 pass 97 98 def __gt__(self, y): # real signature unknown; restored from __doc__ 99 """ x.__gt__(y) <==> x>y """ 100 pass 101 102 def __iadd__(self, y): # real signature unknown; restored from __doc__ 103 """ x.__iadd__(y) <==> x+=y """ 104 pass 105 106 def __imul__(self, y): # real signature unknown; restored from __doc__ 107 """ x.__imul__(y) <==> x*=y """ 108 pass 109 110 def __init__(self, seq=()): # known special case of list.__init__ 111 """ 112 list() -> new empty list 113 list(iterable) -> new list initialized from iterable's items 114 # (copied from class doc) 115 """ 116 pass 117 118 def __iter__(self): # real signature unknown; restored from __doc__ 119 """ x.__iter__() <==> iter(x) """ 120 pass 121 122 def __len__(self): # real signature unknown; restored from __doc__ 123 """ x.__len__() <==> len(x) """ 124 pass 125 126 def __le__(self, y): # real signature unknown; restored from __doc__ 127 """ x.__le__(y) <==> x<=y """ 128 pass 129 130 def __lt__(self, y): # real signature unknown; restored from __doc__ 131 """ x.__lt__(y) <==> x<y """ 132 pass 133 134 def __mul__(self, n): # real signature unknown; restored from __doc__ 135 """ x.__mul__(n) <==> x*n """ 136 pass 137 138 @staticmethod # known case of __new__ 139 def __new__(S, *more): # real signature unknown; restored from __doc__ 140 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 141 pass 142 143 def __ne__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ne__(y) <==> x!=y """ 145 pass 146 147 def __repr__(self): # real signature unknown; restored from __doc__ 148 """ x.__repr__() <==> repr(x) """ 149 pass 150 151 def __reversed__(self): # real signature unknown; restored from __doc__ 152 """ L.__reversed__() -- return a reverse iterator over the list """ 153 pass 154 155 def __rmul__(self, n): # real signature unknown; restored from __doc__ 156 """ x.__rmul__(n) <==> n*x """ 157 pass 158 159 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 160 """ x.__setitem__(i, y) <==> x[i]=y """ 161 pass 162 163 def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ 164 """ 165 x.__setslice__(i, j, y) <==> x[i:j]=y 166 167 Use of negative indices is not supported. 168 """ 169 pass 170 171 def __sizeof__(self): # real signature unknown; restored from __doc__ 172 """ L.__sizeof__() -- size of L in memory, in bytes """ 173 pass 174 175 __hash__ = None 176 177 list
5、元组(不可修改)
创建元组:
ages = (11, 22, 33, 44, 55)
ages = tuple((11, 22, 33, 44, 55))
lass tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. """ def count(self, value): # real signature unknown; restored from __doc__ """ T.count(value) -> integer -- return number of occurrences of value """ return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ T.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, seq=()): # known special case of tuple.__init__ """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ T.__sizeof__() -- size of T in memory, in bytes """ pass tuple
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 # 元组 tuple 6 # 列表 有序 元素可被修改 7 8 # tu = (111, "eric", (11, 22), [(33, 44)], True, 44, 55,) 9 # 1、元组 不可修改,不能被增加或者删除 10 # 2、索引 11 # v = tu[0] 12 # print(v) 13 # 3、切片 14 # v = tu[0:3] 15 # print(v) 16 # 4、for循环,字符串 列表 元组之间转换 元组也是可迭代对象 17 # for item in tu: 18 # print(item) 19 # 5、注意:元组的一级元素不能被修改/删除/增加 如果有二级元素就可以修改 20 # tu = (11, 22, 33, 44,) 21 # 6、count index 22 # v = tu.count(11) 23 # print(v) 24 # v = tu.index(22, 0, 3) 25 # print(v)
6、字典(无序)
创建字典:
person = {"name": "mr.sb", 'age': 18} 或 person = dict({"name": "mr.sb", 'age': 18})
常用操作:
- 索引
- 新增
- 删除
- 键、值、键值对
- 循环
- 长度
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 # 字典 dict 6 # 1、存储方式是哈希表格 7 # key:列表、字典不能作为字典的key 布尔值可以作为key哈有些人搞不对 8 # value:任何都可以 自己创字典例子试把 9 # 2、字典无序 10 # info = { 11 # "k1": 18, 12 # 2: True, 13 # "k3": [11, 14 # 22, 15 # [], 16 # (), 17 # 33, 18 # { 19 # "kk1": "vv1", 20 # "kk2": "vv2", 21 # "kk3": (11, 22), 22 # } 23 # ], 24 # "k4": (11, 22, 33, 44) 25 # } 26 # 3、通过索引取值 27 # print(info) 28 # v = info["k1"] 29 # print(v) 30 # v = info[2] 31 # print(v) 32 # v = info["k3"][5]["kk3"][0] 33 # print(v) 34 # 4、删除键 35 # del info["k3"][5]["kk1"] 36 # print(info) 37 # 5、for循环 38 # dict 默认拿key 39 # for item in info: 40 # print(item) 41 # for item in info.keys(): 42 # print(item) 43 # for item in info.values(): 44 # print(item) 45 # for item in info.keys(): 46 # print(item, info[item]) 47 # 这样拿到的是一个个元组 48 # for item in info.items(): 49 # print(item) 50 # for k, v in info.items(): 51 # print(k, v) 52 53 54 # 方法 清空 浅拷贝 55 dic = { 56 "k1": "v1", 57 "k2": "v2" 58 } 59 # 创建字典 {'k1': 123, 123: 123, '999': 123} 60 # v = dict.fromkeys(["k1", 123, "999"], 123) 61 # print(v) 62 # v = dic.get('k1111') 63 # print(v) # None 64 # v = dic.pop('k1') 65 # print(dic, v) 66 # popitem()随机删除,并获取值 67 # k, v = dic.popitem() 68 # print(dic, k, v) 69 # 设置值 如果存在就不做操作 如果不存在就设置值 70 # v = dic.setdefault('k3', '123') 71 # print(dic, v) 72 # 更新 73 # dic.update({"k1": "1111", "k3": 123}) 74 # print(dic) 75 # dic.update(k1=123) 76 # print(dic)
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ 清除内容 """ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 浅拷贝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根据key获取值,d是默认值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 所有项的列表形式 """ """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 项可迭代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可迭代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可迭代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D's keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {'name':'alex', 'age': 18000} [('name','sbsbsb'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D's values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 所有项,只是将内容保存至view对象中 """ """ D.viewitems() -> a set-like object providing a view on D's items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D's keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D's values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None dict
7、集合(set 无序 不重复)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 # 集合 set 6 7 # 可变类型:值被修改后,id没变(列表,字典) 8 # 不可变类型:修改变量的值id改变 (字符串,数字,元组) 9 # 有序:str list tuple 10 # 无序:dict 11 # 集合特征:1.不同元素组成(无重复)2.无序3.元素必须是不可变类型 12 # 创建 13 # s = set('hello') 14 # print(s) 15 # s = {1, 2, 3} 16 # print(s, type(s)) 17 # 内置方法 18 # s = {'sb', 1, 2, 3, 4, 5, 6} 19 # s.add(7) 20 # s.clear() 21 # v = s.copy() 22 # print(v) 23 # 无序随机删除 24 # s.pop() 25 # 指定删除 remove删除不存在的元素就要报错 discard删除的元素不存在是不会报错 26 # s.remove('sb') 27 # s.discard('sbbbbbb') 28 # print(s) 29 # python_l = ['sb', 'eric', '藏獒', 'sb'] 30 # linux_l = ['sb', '藏獒', 'erb'] 31 # 32 # p_s = set(python_l) 33 # l_s = set(linux_l) 34 # 求交集 35 # print(p_s.intersection(l_s)) 36 # print(p_s & l_s) 37 38 # 求并集 39 # print(p_s.union(l_s)) 40 # print(p_s | l_s) 41 42 # 求差集 43 # print(p_s - l_s) 44 # print(p_s.difference(l_s)) 45 46 # 交叉补集 47 # print(p_s.symmetric_difference(l_s)) 48 # print(p_s ^ l_s) 49 50 # update更新 51 # s1 = {1, 2} 52 # s2 = {1, 2, 3} 53 # s1.update(s2) 54 # print(s1) 55 56 s = frozenset('hello') # 不可变,普通集合就是可变类型 57 print(s) 58 # 简单去重的话就用集合操作 如果要求顺序啊哪些就不要用集合了
class set(object): """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. """ def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set. This has no effect if the element is already present. """ pass def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from this set. """ pass def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. """ pass def discard(self, *args, **kwargs): # real signature unknown """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ pass def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. """ pass def pop(self, *args, **kwargs): # real signature unknown """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass def remove(self, *args, **kwargs): # real signature unknown """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iand__(self, *args, **kwargs): # real signature unknown """ Return self&=value. """ pass def __init__(self, seq=()): # known special case of set.__init__ """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass def __ior__(self, *args, **kwargs): # real signature unknown """ Return self|=value. """ pass def __isub__(self, *args, **kwargs): # real signature unknown """ Return self-=value. """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __ixor__(self, *args, **kwargs): # real signature unknown """ Return self^=value. """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass __hash__ = None
其它
1、for循环
1 li = [11, 22, 33, 44] 2 for item in li: 3 print(item)
2、enumrate
为可迭代的对象添加序号
1 li = [11, 22, 33] 2 for k, v in enumerate(li, 1): 3 print(k, v)
3、range和xrange
指定范围 ,xrange返回的是一个可迭代的对象,range返回的则是一个列表. 同时效率更高,更快。
1 print(range(1, 10)) 2 # 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9] 3 4 print(range(1, 10, 2)) 5 # 结果:[1, 3, 5, 7, 9] 6 7 print(range(30, 0, -2)) 8 # 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]