python基础-2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
1、编码转换
unicode 可以编译成 UTF-U GBK
即
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = '测试字符' #默认是utf-8 4 a_unicode = a.decode('utf-8') # decode是解码成unicode 括号是脚本内容的默认编码 即:将脚本内容的utf-8解码成unicode 5 a_gbk = a_unicode.encode('gbk') #encode是编码,将unicode的编码内容编码成指定的,这里是gbk 6 print(a_gbk) #用于终端打印 7 print(u"测试字符二") #3里面是字符串 2里面是unicode
#3版本直接将utf-8编码成GBK 不需要先转成unicode了
2、pycharm的基本配置
1、file-setings-editor- file && file encode template Python Script输入 以下内容作为声明模板
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_
2、View-Active Editor 勾选Use Soft Wraps 开启自动换行
3、在设置中,搜索encoding,可以修改编码规则
4、简单的快捷键
ctrl+/ 批量注释,取消注释
shift+方向键 选中
shift+tab 向左tab
5、
切换py版本
file -> settings ->project interpreter ->选择版本
3、运算符
1、算数运算:
2、比较运算:
3、赋值运算:
4、逻辑运算:
5、成员运算:
运算符 |
名称 |
说明 |
例子 |
+ |
加 |
两个对象相加 |
3 + 5得到8。'a' + 'b'得到'ab'。 |
- |
减 |
得到负数或是一个数减去另一个数 |
-5.2得到一个负数。50 - 24得到26。 |
* |
乘 |
两个数相乘或是返回一个被重复若干次的字符串 |
2 * 3得到6。'la' * 3得到'lalala'。 |
** |
幂 |
返回x的y次幂 |
3 ** 4得到81(即3 * 3 * 3 * 3) |
/ |
除 |
x除以y |
4/3得到1(整数的除法得到整数结果)。4.0/3或4/3.0得到1.3333333333333333 |
// |
取整除 |
返回商的整数部分 |
4 // 3.0得到1.0 |
% |
取模 |
返回除法的余数 |
8%3得到2。-25.5%2.25得到1.5 |
<< |
左移 |
把一个数的比特向左移一定数目(每个数在内存中都表示为比特或二进制数字,即0和1) |
2 << 2得到8。——2按比特表示为10 |
>> |
右移 |
把一个数的比特向右移一定数目 |
11 >> 1得到5。——11按比特表示为1011,向右移动1比特后得到101,即十进制的5。 |
& |
按位与 |
数的按位与 |
5 & 3得到1。 |
| |
按位或 |
数的按位或 |
5 | 3得到7。 |
^ |
按位异或 |
数的按位异或 |
5 ^ 3得到6 |
~ |
按位翻转 |
x的按位翻转是-(x+1) |
~5得到-6。 |
< |
小于 |
返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 |
5 < 3返回0(即False)而3 < 5返回1(即True)。比较可以被任意连接:3 < 5 < 7返回True。 |
> |
大于 |
返回x是否大于y |
5 > 3返回True。如果两个操作数都是数字,它们首先被转换为一个共同的类型。否则,它总是返回False。 |
<= |
小于等于 |
返回x是否小于等于y |
x = 3; y = 6; x <= y返回True。 |
>= |
大于等于 |
返回x是否大于等于y |
x = 4; y = 3; x >= y返回True。 |
== |
等于 |
比较对象是否相等 |
x = 2; y = 2; x == y返回True。x = 'str'; y = 'stR'; x == y返回False。x = 'str'; y = 'str'; x == y返回True。 |
!= |
不等于 |
比较两个对象是否不相等 |
x = 2; y = 3; x != y返回True。 |
not |
布尔“非” |
如果x为True,返回False。如果x为False,它返回True。 |
x = True; not x返回False。 |
and |
布尔“与” |
如果x为False,x and y返回False,否则它返回y的计算值。 |
x = False; y = True; x and y,由于x是False,返回False。在这里,Python不会计算y,因为它知道这个表达式的值肯定是False(因为x是False)。这个现象称为短路计算。 |
or |
布尔“或” |
如果x是True,它返回True,否则它返回y的计算值。 |
x = True; y = False; x or y返回True。短路计算在这里也适用。 |
4、基本的数据类型
数字的方法都放在int类中,而数字是类的实例化。 如上图所示。
可以通过type(a),来查看数据类型,变量的地址用id(a),来查看
int(整型)
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
1 class int(object): 2 """ 3 int(x=0) -> int or long 4 int(x, base=10) -> int or long 5 6 Convert a number or string to an integer, or return 0 if no arguments 7 are given. If x is floating point, the conversion truncates towards zero. 8 If x is outside the integer range, the function returns a long instead. 9 10 If x is not a number or if base is given, then x must be a string or 11 Unicode object representing an integer literal in the given base. The 12 literal can be preceded by '+' or '-' and be surrounded by whitespace. 13 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 14 interpret the base from the string as an integer literal. 15 >>> int('0b100', base=0) 16 """ 17 def bit_length(self): 18 """ 返回表示该数字的时占用的最少位数 """ 19 """ 20 int.bit_length() -> int 21 22 Number of bits necessary to represent self in binary. 23 >>> bin(37) 24 '0b100101' 25 >>> (37).bit_length() 26 """ 27 return 0 28 29 def conjugate(self, *args, **kwargs): # real signature unknown 30 """ 返回该复数的共轭复数 """ 31 """ Returns self, the complex conjugate of any int. """ 32 pass 33 34 def __abs__(self): 35 """ 返回绝对值 """ 36 """ x.__abs__() <==> abs(x) """ 37 pass 38 39 def __add__(self, y): 40 """ x.__add__(y) <==> x+y """ 41 pass 42 43 def __and__(self, y): 44 """ x.__and__(y) <==> x&y """ 45 pass 46 47 def __cmp__(self, y): 48 """ 比较两个数大小 """ 49 """ x.__cmp__(y) <==> cmp(x,y) """ 50 pass 51 52 def __coerce__(self, y): 53 """ 强制生成一个元组 """ 54 """ x.__coerce__(y) <==> coerce(x, y) """ 55 pass 56 57 def __divmod__(self, y): 58 """ 相除,得到商和余数组成的元组 """ 59 """ x.__divmod__(y) <==> divmod(x, y) """ 60 pass 61 62 def __div__(self, y): 63 """ x.__div__(y) <==> x/y """ 64 pass 65 66 def __float__(self): 67 """ 转换为浮点类型 """ 68 """ x.__float__() <==> float(x) """ 69 pass 70 71 def __floordiv__(self, y): 72 """ x.__floordiv__(y) <==> x//y """ 73 pass 74 75 def __format__(self, *args, **kwargs): # real signature unknown 76 pass 77 78 def __getattribute__(self, name): 79 """ x.__getattribute__('name') <==> x.name """ 80 pass 81 82 def __getnewargs__(self, *args, **kwargs): # real signature unknown 83 """ 内部调用 __new__方法或创建对象时传入参数使用 """ 84 pass 85 86 def __hash__(self): 87 """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" 88 """ x.__hash__() <==> hash(x) """ 89 pass 90 91 def __hex__(self): 92 """ 返回当前数的 十六进制 表示 """ 93 """ x.__hex__() <==> hex(x) """ 94 pass 95 96 def __index__(self): 97 """ 用于切片,数字无意义 """ 98 """ x[y:z] <==> x[y.__index__():z.__index__()] """ 99 pass 100 101 def __init__(self, x, base=10): # known special case of int.__init__ 102 """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 103 """ 104 int(x=0) -> int or long 105 int(x, base=10) -> int or long 106 107 Convert a number or string to an integer, or return 0 if no arguments 108 are given. If x is floating point, the conversion truncates towards zero. 109 If x is outside the integer range, the function returns a long instead. 110 111 If x is not a number or if base is given, then x must be a string or 112 Unicode object representing an integer literal in the given base. The 113 literal can be preceded by '+' or '-' and be surrounded by whitespace. 114 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to 115 interpret the base from the string as an integer literal. 116 >>> int('0b100', base=0) 117 # (copied from class doc) 118 """ 119 pass 120 121 def __int__(self): 122 """ 转换为整数 """ 123 """ x.__int__() <==> int(x) """ 124 pass 125 126 def __invert__(self): 127 """ x.__invert__() <==> ~x """ 128 pass 129 130 def __long__(self): 131 """ 转换为长整数 """ 132 """ x.__long__() <==> long(x) """ 133 pass 134 135 def __lshift__(self, y): 136 """ x.__lshift__(y) <==> x<<y """ 137 pass 138 139 def __mod__(self, y): 140 """ x.__mod__(y) <==> x%y """ 141 pass 142 143 def __mul__(self, y): 144 """ x.__mul__(y) <==> x*y """ 145 pass 146 147 def __neg__(self): 148 """ x.__neg__() <==> -x """ 149 pass 150 151 @staticmethod # known case of __new__ 152 def __new__(S, *more): 153 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 154 pass 155 156 def __nonzero__(self): 157 """ x.__nonzero__() <==> x != 0 """ 158 pass 159 160 def __oct__(self): 161 """ 返回改值的 八进制 表示 """ 162 """ x.__oct__() <==> oct(x) """ 163 pass 164 165 def __or__(self, y): 166 """ x.__or__(y) <==> x|y """ 167 pass 168 169 def __pos__(self): 170 """ x.__pos__() <==> +x """ 171 pass 172 173 def __pow__(self, y, z=None): 174 """ 幂,次方 """ 175 """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ 176 pass 177 178 def __radd__(self, y): 179 """ x.__radd__(y) <==> y+x """ 180 pass 181 182 def __rand__(self, y): 183 """ x.__rand__(y) <==> y&x """ 184 pass 185 186 def __rdivmod__(self, y): 187 """ x.__rdivmod__(y) <==> divmod(y, x) """ 188 pass 189 190 def __rdiv__(self, y): 191 """ x.__rdiv__(y) <==> y/x """ 192 pass 193 194 def __repr__(self): 195 """转化为解释器可读取的形式 """ 196 """ x.__repr__() <==> repr(x) """ 197 pass 198 199 def __str__(self): 200 """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" 201 """ x.__str__() <==> str(x) """ 202 pass 203 204 def __rfloordiv__(self, y): 205 """ x.__rfloordiv__(y) <==> y//x """ 206 pass 207 208 def __rlshift__(self, y): 209 """ x.__rlshift__(y) <==> y<<x """ 210 pass 211 212 def __rmod__(self, y): 213 """ x.__rmod__(y) <==> y%x """ 214 pass 215 216 def __rmul__(self, y): 217 """ x.__rmul__(y) <==> y*x """ 218 pass 219 220 def __ror__(self, y): 221 """ x.__ror__(y) <==> y|x """ 222 pass 223 224 def __rpow__(self, x, z=None): 225 """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ 226 pass 227 228 def __rrshift__(self, y): 229 """ x.__rrshift__(y) <==> y>>x """ 230 pass 231 232 def __rshift__(self, y): 233 """ x.__rshift__(y) <==> x>>y """ 234 pass 235 236 def __rsub__(self, y): 237 """ x.__rsub__(y) <==> y-x """ 238 pass 239 240 def __rtruediv__(self, y): 241 """ x.__rtruediv__(y) <==> y/x """ 242 pass 243 244 def __rxor__(self, y): 245 """ x.__rxor__(y) <==> y^x """ 246 pass 247 248 def __sub__(self, y): 249 """ x.__sub__(y) <==> x-y """ 250 pass 251 252 def __truediv__(self, y): 253 """ x.__truediv__(y) <==> x/y """ 254 pass 255 256 def __trunc__(self, *args, **kwargs): 257 """ 返回数值被截取为整形的值,在整形中无意义 """ 258 pass 259 260 def __xor__(self, y): 261 """ x.__xor__(y) <==> x^y """ 262 pass 263 264 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 265 """ 分母 = 1 """ 266 """the denominator of a rational number in lowest terms""" 267 268 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 269 """ 虚数,无意义 """ 270 """the imaginary part of a complex number""" 271 272 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 273 """ 分子 = 数字大小 """ 274 """the numerator of a rational number in lowest terms""" 275 276 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 277 """ 实属,无意义 """ 278 """the real part of a complex number""" 279 280 int
1 "hello world"
字符串格式化
1 name = "alex" 2 print "i am %s " % name 3 4 #输出: i am alex
PS: 字符串是 %s;整数 %d;浮点数%f。浮点数小数位数%.2f 保留小数点后2位 %%s 百分号
单引号,双引号都可以表示字符串,里面可以插入另外的引号。三引号也可以表示字符串,支持换行的。
- 移除空白
- strip
- 分割
- partition
- 长度
- len(s)
- 索引
-
s="alex"s[0] #拿第0个元素,取一个元素
-
- 切片
-
s[0:2] # 0<=取值<2,取多个元素,顾头不顾尾原则,顾前不顾后s[0:2:2] 步长。
- 切片倒序 是s[::-1],切片的起始和结束如果不填就是默认全部,步长-1就是反向。
-
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 """ 22 return "" 23 24 def casefold(self): # real signature unknown; restored from __doc__ 25 """ 26 S.casefold() -> str 27 28 Return a version of S suitable for caseless comparisons. 29 """ 30 return "" 31 32 def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ 33 """ 可以为字符串 填充自定字符 长度=字符+指定字符 34 S.center(width[, fillchar]) -> str 35 36 Return S centered in a string of length width. Padding is 37 done using the specified fill character (default is a space) 38 """ 39 return "" 40 41 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 42 """ 下面是详细参数: 43 子串:是要搜索的子串。 44 45 开始:从该指数开始搜索。第一个字符从索引0开始。通过默认搜索引擎从索引0开始。 46 47 结束:搜索从该指数结束。第一个字符从索引0开始。默认情况下,搜索结束,在最后一个索引。 48 49 50 S.count(sub[, start[, end]]) -> int 51 52 Return the number of non-overlapping occurrences of substring sub in 53 string S[start:end]. Optional arguments start and end are 54 interpreted as in slice notation. 55 """ 56 return 0 57 58 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ 59 """ 编码 上面有介绍 60 S.encode(encoding='utf-8', errors='strict') -> bytes 61 62 Encode S using the codec registered for encoding. Default encoding 63 is 'utf-8'. errors may be given to set a different error 64 handling scheme. Default is 'strict' meaning that encoding errors raise 65 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 66 'xmlcharrefreplace' as well as any other name registered with 67 codecs.register_error that can handle UnicodeEncodeErrors. 68 """ 69 return b"" 70 71 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ 72 """ 以 某个字符结束 73 suffix -- 该参数可以是一个字符串或者是一个元素。 74 75 start -- 字符串中的开始位置。 76 77 end -- 字符中结束位置。 78 79 80 81 返回值 82 83 84 85 如果字符串含有指定的后缀返回True,否则返回False。 86 87 88 89 S.endswith(suffix[, start[, end]]) -> bool 90 91 Return True if S ends with the specified suffix, False otherwise. 92 With optional start, test S beginning at that position. 93 With optional end, stop comparing S at that position. 94 suffix can also be a tuple of strings to try. 95 """ 96 return False 97 98 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ 99 """ 把tab转换成空格 100 S.expandtabs(tabsize=8) -> str 101 102 Return a copy of S where all tab characters are expanded using spaces. 103 If tabsize is not given, a tab size of 8 characters is assumed. 104 """ 105 return "" 106 107 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 108 """ 109 find(str, pos_start, pos_end) 110 111 解释: 112 113 str:被查找“字串” 114 115 pos_start:查找的首字母位置(从0开始计数。默认:0) 116 117 pos_end: 查找的末尾位置(默认-1) 118 119 返回值:如果查到:返回查找的第一个出现的位置。否则,返回-1。 120 121 122 123 S.find(sub[, start[, end]]) -> int 124 125 Return the lowest index in S where substring sub is found, 126 such that sub is contained within S[start:end]. Optional 127 arguments start and end are interpreted as in slice notation. 128 129 Return -1 on failure. 130 """ 131 return 0 132 133 def format(*args, **kwargs): # known special case of str.format 134 """ 占位符 类似变量引用 135 s = "print hell {0} ,age {1}" 136 print(s.format('alex',19)) 137 138 139 S.format(*args, **kwargs) -> str 140 141 Return a formatted version of S, using substitutions from args and kwargs. 142 The substitutions are identified by braces ('{' and '}'). 143 """ 144 pass 145 146 def format_map(self, mapping): # real signature unknown; restored from __doc__ 147 """字符串格式化,动态参数,将函数式编程时细说 148 S.format_map(mapping) -> str 149 150 Return a formatted version of S, using substitutions from mapping. 151 The substitutions are identified by braces ('{' and '}'). 152 """ 153 return "" 154 155 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 156 """ #跟find类似但是 没有找到的话会报错。 而find是返回-1 157 S.index(sub[, start[, end]]) -> int 158 159 Like S.find() but raise ValueError when the substring is not found. 160 """ 161 return 0 162 163 def isalnum(self): # real signature unknown; restored from __doc__ 164 """ #判断是否是数字和字母 165 S.isalnum() -> bool 166 167 Return True if all characters in S are alphanumeric 168 and there is at least one character in S, False otherwise. 169 """ 170 return False 171 172 def isalpha(self): # real signature unknown; restored from __doc__ 173 """是否是字母 174 S.isalpha() -> bool 175 176 Return True if all characters in S are alphabetic 177 and there is at least one character in S, False otherwise. 178 """ 179 return False 180 181 def isdecimal(self): # real signature unknown; restored from __doc__ 182 """ 183 S.isdecimal() -> bool 184 185 Return True if there are only decimal characters in S, 186 False otherwise. 187 """ 188 return False 189 190 def isdigit(self): # real signature unknown; restored from __doc__ 191 """ 是否是数字 192 S.isdigit() -> bool 193 194 Return True if all characters in S are digits 195 and there is at least one character in S, False otherwise. 196 """ 197 return False 198 199 def isidentifier(self): # real signature unknown; restored from __doc__ 200 """ 201 S.isidentifier() -> bool 202 203 Return True if S is a valid identifier according 204 to the language definition. 205 206 Use keyword.iskeyword() to test for reserved identifiers 207 such as "def" and "class". 208 """ 209 return False 210 211 def islower(self): # real signature unknown; restored from __doc__ 212 """是否小写字母 213 S.islower() -> bool 214 215 Return True if all cased characters in S are lowercase and there is 216 at least one cased character in S, False otherwise. 217 """ 218 return False 219 220 def isnumeric(self): # real signature unknown; restored from __doc__ 221 """ 222 S.isnumeric() -> bool 223 224 Return True if there are only numeric characters in S, 225 False otherwise. 226 """ 227 return False 228 229 def isprintable(self): # real signature unknown; restored from __doc__ 230 """ 231 S.isprintable() -> bool 232 233 Return True if all characters in S are considered 234 printable in repr() or S is empty, False otherwise. 235 """ 236 return False 237 238 def isspace(self): # real signature unknown; restored from __doc__ 239 """是否是空格 240 S.isspace() -> bool 241 242 Return True if all characters in S are whitespace 243 and there is at least one character in S, False otherwise. 244 """ 245 return False 246 247 def istitle(self): # real signature unknown; restored from __doc__ 248 """ 是否是标题 字符串开头是大写 后面是小写 249 S.istitle() -> bool 250 251 Return True if S is a titlecased string and there is at least one 252 character in S, i.e. upper- and titlecase characters may only 253 follow uncased characters and lowercase characters only cased ones. 254 Return False otherwise. 255 """ 256 return False 257 258 def isupper(self): # real signature unknown; restored from __doc__ 259 """ 是否是大写 260 S.isupper() -> bool 261 262 Return True if all cased characters in S are uppercase and there is 263 at least one cased character in S, False otherwise. 264 """ 265 return False 266 267 def join(self, iterable): # real signature unknown; restored from __doc__ 268 """ 拼接 后面有例子 269 270 S.join(iterable) -> str 271 272 Return a string which is the concatenation of the strings in the 273 iterable. The separator between elements is S. 274 """ 275 return "" 276 277 def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ 278 """ 内容左对齐,右侧填充""" 279 """ 280 ljust()方法语法: 281 282 str.ljust(width[, fillchar]) 283 284 参数 285 286 width -- 指定字符串长度。 287 288 fillchar -- 填充字符,默认为空格。 289 290 返回值 291 292 返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。 293 294 S.ljust(width[, fillchar]) -> str 295 Return S left-justified in a Unicode string of length width.Padding is done using the specified fill character (default is a space). 296 """ 297 return "" 298 299 def lower(self): # real signature unknown; restored from __doc__ 300 """ 转换为小写 301 S.lower() -> str 302 Return a copy of the string S converted to lowercase. 303 """ 304 return "" 305 306 def lstrip(self, chars=None): # real signature unknown; restored from __doc__ 307 """ 去除左侧开头空白 308 S.lstrip([chars]) -> str 309 Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. 310 """ 311 return "" 312 313 def maketrans(self, *args, **kwargs): # real signature unknown 314 """ Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. 315 """ 316 pass 317 318 def partition(self, sep): # real signature unknown; restored from __doc__ 319 """ 以指定 字符 开始分割 指定的字符也显示 320 S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. 321 """ 322 pass 323 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ 324 """ 替换 325 old -- 将被替换的子字符串。 326 327 new -- 新字符串,用于替换old子字符串。 328 329 max -- 可选字符串, 替换不超过 max 次 330 331 返回值 332 333 返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。 334 335 S.replace(old, new[, count]) -> str 336 337 Return a copy of S with all occurrences of substring 338 old replaced by new. If the optional argument count is 339 given, only the first count occurrences are replaced. 340 """ 341 return "" 342 343 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 344 """ 从右开始查找 345 S.rfind(sub[, start[, end]]) -> int 346 347 Return the highest index in S where substring sub is found, 348 such that sub is contained within S[start:end]. Optional 349 arguments start and end are interpreted as in slice notation. 350 351 Return -1 on failure. 352 """ 353 return 0 354 355 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 356 """ 顾名思义从右侧匹配 357 S.rindex(sub[, start[, end]]) -> int 358 359 Like S.rfind() but raise ValueError when the substring is not found. 360 """ 361 return 0 362 363 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ 364 """ 从右侧 填充 365 S.rjust(width[, fillchar]) -> str 366 367 Return S right-justified in a string of length width. Padding is 368 done using the specified fill character (default is a space). 369 """ 370 return "" 371 372 def rpartition(self, sep): # real signature unknown; restored from __doc__ 373 """ 从右侧开始找到 分割 分割字符也显示 374 S.rpartition(sep) -> (head, sep, tail) 375 376 Search for the separator sep in S, starting at the end of S, and return 377 the part before it, the separator itself, and the part after it. If the 378 separator is not found, return two empty strings and S. 379 """ 380 pass 381 382 def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 383 """ 从右侧开始分割 sep是指定几个 384 S.rsplit(sep=None, maxsplit=-1) -> list of strings 385 386 Return a list of the words in S, using sep as the 387 delimiter string, starting at the end of the string and 388 working to the front. If maxsplit is given, at most maxsplit 389 splits are done. If sep is not specified, any whitespace string 390 is a separator. 391 """ 392 return [] 393 394 def rstrip(self, chars=None): # real signature unknown; restored from __doc__ 395 """ 从右侧 去除结尾的空格 396 S.rstrip([chars]) -> str 397 398 Return a copy of the string S with trailing whitespace removed. 399 If chars is given and not None, remove characters in chars instead. 400 """ 401 return "" 402 403 def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 404 """ 分割 sep是几个算分割符 405 S.split(sep=None, maxsplit=-1) -> list of strings 406 407 Return a list of the words in S, using sep as the 408 delimiter string. If maxsplit is given, at most maxsplit 409 splits are done. If sep is not specified or is None, any 410 whitespace string is a separator and empty strings are 411 removed from the result. 412 """ 413 return [] 414 415 def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ 416 """ 417 S.splitlines([keepends]) -> list of strings 418 419 Return a list of the lines in S, breaking at line boundaries. 420 Line breaks are not included in the resulting list unless keepends 421 is given and true. 422 """ 423 return [] 424 425 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ 426 """ 指定以什么开始 427 S.startswith(prefix[, start[, end]]) -> bool 428 429 Return True if S starts with the specified prefix, False otherwise. 430 With optional start, test S beginning at that position. 431 With optional end, stop comparing S at that position. 432 prefix can also be a tuple of strings to try. 433 """ 434 return False 435 436 def strip(self, chars=None): # real signature unknown; restored from __doc__ 437 """ 去除两端空格 438 S.strip([chars]) -> str 439 440 Return a copy of the string S with leading and trailing 441 whitespace removed. 442 If chars is given and not None, remove characters in chars instead. 443 """ 444 return "" 445 446 def swapcase(self): # real signature unknown; restored from __doc__ 447 """ 大写转小写小写转大写 448 S.swapcase() -> str 449 450 Return a copy of S with uppercase characters converted to lowercase 451 and vice versa. 452 """ 453 return "" 454 455 def title(self): # real signature unknown; restored from __doc__ 456 """ 457 S.title() -> str 458 459 Return a titlecased version of S, i.e. words start with title case 460 characters, all remaining cased characters have lower case. 461 """ 462 return "" 463 464 def translate(self, table): # real signature unknown; restored from __doc__ 465 """ 466 467 468 转换,需要先做一个对应表,最后一个表示删除字符集合 469 intab = "aeiou" 470 outtab = "12345" 471 trantab = maketrans(intab, outtab) 472 str = "this is string example....wow!!!"print str.translate(trantab, 'xm') 473 474 475 476 477 S.translate(table) -> str 478 479 Return a copy of the string S in which each character has been mapped 480 through the given translation table. The table must implement 481 lookup/indexing via __getitem__, for instance a dictionary or list, 482 mapping Unicode ordinals to Unicode ordinals, strings, or None. If 483 this operation raises LookupError, the character is left untouched. 484 Characters mapped to None are deleted. 485 """ 486 return "" 487 488 def upper(self): # real signature unknown; restored from __doc__ 489 """ 大写显示 490 S.upper() -> str 491 492 Return a copy of S converted to uppercase. 493 """ 494 return "" 495 496 def zfill(self, width): # real signature unknown; restored from __doc__ 497 """ 方法返回指定长度的字符串,原字符串右对齐,前面填充0。 498 S.zfill(width) -> str 499 500 Pad a numeric string S with zeros on the left, to fill a field 501 of the specified width. The string S is never truncated. 502 """ 503 return "" 504 505 def __add__(self, *args, **kwargs): # real signature unknown 506 """ Return self+value. """ 507 pass 508 509 def __contains__(self, *args, **kwargs): # real signature unknown 510 """ Return key in self. """ 511 pass 512 513 def __eq__(self, *args, **kwargs): # real signature unknown 514 """ Return self==value. """ 515 pass 516 517 def __format__(self, format_spec): # real signature unknown; restored from __doc__ 518 """ 519 S.__format__(format_spec) -> str 520 521 Return a formatted version of S as described by format_spec. 522 """ 523 return "" 524 525 def __getattribute__(self, *args, **kwargs): # real signature unknown 526 """ Return getattr(self, name). """ 527 pass 528 529 def __getitem__(self, *args, **kwargs): # real signature unknown 530 """ Return self[key]. """ 531 pass 532 533 def __getnewargs__(self, *args, **kwargs): # real signature unknown 534 pass 535 536 def __ge__(self, *args, **kwargs): # real signature unknown 537 """ Return self>=value. """ 538 pass 539 540 def __gt__(self, *args, **kwargs): # real signature unknown 541 """ Return self>value. """ 542 pass 543 544 def __hash__(self, *args, **kwargs): # real signature unknown 545 """ Return hash(self). """ 546 pass 547 548 def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__ 549 """ 550 str(object='') -> str 551 str(bytes_or_buffer[, encoding[, errors]]) -> str 552 553 Create a new string object from the given object. If encoding or 554 errors is specified, then the object must expose a data buffer 555 that will be decoded using the given encoding and error handler. 556 Otherwise, returns the result of object.__str__() (if defined) 557 or repr(object). 558 encoding defaults to sys.getdefaultencoding(). 559 errors defaults to 'strict'. 560 # (copied from class doc) 561 """ 562 pass 563 564 def __iter__(self, *args, **kwargs): # real signature unknown 565 """ Implement iter(self). """ 566 pass 567 568 def __len__(self, *args, **kwargs): # real signature unknown 569 """ Return len(self). """ 570 pass 571 572 def __le__(self, *args, **kwargs): # real signature unknown 573 """ Return self<=value. """ 574 pass 575 576 def __lt__(self, *args, **kwargs): # real signature unknown 577 """ Return self<value. """ 578 pass 579 580 def __mod__(self, *args, **kwargs): # real signature unknown 581 """ Return self%value. """ 582 pass 583 584 def __mul__(self, *args, **kwargs): # real signature unknown 585 """ Return self*value.n """ 586 pass 587 588 @staticmethod # known case of __new__ 589 def __new__(*args, **kwargs): # real signature unknown 590 """ Create and return a new object. See help(type) for accurate signature. """ 591 pass 592 593 def __ne__(self, *args, **kwargs): # real signature unknown 594 """ Return self!=value. """ 595 pass 596 597 def __repr__(self, *args, **kwargs): # real signature unknown 598 """ Return repr(self). """ 599 pass 600 601 def __rmod__(self, *args, **kwargs): # real signature unknown 602 """ Return value%self. """ 603 pass 604 605 def __rmul__(self, *args, **kwargs): # real signature unknown 606 """ Return self*value. """ 607 pass 608 609 def __sizeof__(self): # real signature unknown; restored from __doc__ 610 """ S.__sizeof__() -> size of S in memory, in bytes """ 611 pass 612 613 def __str__(self, *args, **kwargs): # real signature unknown 614 """ Return str(self). """ 615 pass
字符串练习
#!/usr/bin/env python # -*- coding:utf-8 -*- # str字符串方法练习 a = "alex" ret = a.capitalize() # 不用添加参数,字符串首字母变大写,str(object='') -> string print(ret) ret1 = a.center(20, "*") # 内容居中,width:总长度;fillchar:空白处填充内容,默认无。S.center(width[, fillchar]) -> string print(ret1) a2 = "alex is alph" ret2 = a2.count("al") # 计算子序列个数,def count(self, sub, start=None, end=None):,可定义开始和结束位置。S.count(sub[, start[, end]]) -> int ret3 = a2.count("a", 0) print(ret2, ret3) ret4 = a2.endswith("alp", 0,-1) # """ 是否以 xxx 结束 """endswith(self, suffix, start=None, end=None):,可定义开始和结束的位置,S.endswith(suffix[, start[, end]]) -> bool print(a2.startswith("a")) # """ 是否以 xxx 开始 """ startswith(self, prefix, start=None, end=None):,可定义开始和结束的位置,S.startswith(prefix[, start[, end]]) -> bool print(ret4) a3 = "hello\t999" # """ 将tab转换成空格,默认一个tab转换成8个空格 """def expandtabs(self, tabsize=None):可以定义空格个数,S.expandtabs([tabsize]) -> string print(a3) print(a3.expandtabs(20)) s = "hello alex" s.find("al") # """ 寻找子序列位置,如果没找到,返回 -1 """def find(self, sub, start=None, end=None):可以定义开始和结束的位置,S.find(sub [,start [,end]]) -> int print(s.find("al")) s1 = "hello {0},age {1}" # {0},{1}可以充当占位符 a4 = s1.format("alex",18) # """ 字符串格式化,动态参数,将函数式编程时细说 """def format(*args, **kwargs):S.format(*args, **kwargs) -> string print(s1, a4) print(s.index("ll")) # """ 子序列位置,如果没找到,报错 """ def index(self, sub, start=None, end=None):可以定义开始和结束的位置,S.index(sub [,start [,end]]) -> int num1 = "dasfsdfaa" num2 = "jkljljl" num3 = "57876" num4 = "kkk* &687689" num5 = " " num6 = "Alss Sss 888&&&L " num7 = "ALJL" print(num1.isalnum()) # """ 是否是字母或数字组成"""必须要字母和数字组成的字符串,含有其他字符返回FalseS.isalnum() -> bool print(num2.isalpha()) # """ 是否全是字母 """ print(num3.isdigit()) # """ 是否全是数字 """ print(num4.islower()) # """ 这里面的字母是否小写 """可以包含其他字符 print(num5.isspace()) # 是否全是空格,且自少有一个字符 print(num6.istitle()) # 是否是标题,所有首字母都是大写 print(num7.title()) # 变成标题 print(num7.isupper()) # 是否全是大写 li = ["alex", "eric"] li2 = ("alex", "eric") print("_".join(li2)) # """ 连接 """def join(self, iterable): 参数是可迭代的,循环li的元素,让每个元素用“_”连接起来 pp = "alexKKK000***1111" print(pp.ljust(20, "*")) # """ 内容左对齐,右侧填充 """width:总长度;fillchar:空白处填充内容,默认无。-> string print(pp.rjust(20, "*")) # 内容右对齐 print(pp.lower()) # 字母全部变成小写-> string print(pp.upper()) # 字母全部变成大写-> string print(pp.swapcase()) # 小写变大写,大写变小写 kb = " kkkkfasdfa jkljlk " print(kb.lstrip()) # """ 移除左侧空白 """ print(kb.rstrip()) # """ 移除右侧空白 """ print(kb.strip()) # """ 移除两侧的空白 """ sb = "alex SB alex SB" print(sb.partition("SB")) # """ 分割,前,中,后三部分 """添加到一个元祖里面S.partition(sep) -> (head, sep, tail) print(sb.replace("SB", "HH")) # """ 替换 """count参数是替换几个的意思 print(sb.replace("SB", "HH", 1)) fg = "alexalex" print(fg.split("e")) # """ 分割, maxsplit最多分割几次 """S.split([sep [,maxsplit]]) -> list of strings print(fg.split("e", 1)) fg1 = "alex\nalex" print(fg.splitlines()) # """ 根据换行分割 """
“jljl$ fsaldkfj6sdfjlasjdl”.title 数字特殊字符空格割开的第一个字母大写。
print("abalex".strip("a")) out:balex 。
print("aba*lex*".strip("a*")) out:ba*lex。
4、列表
创建列表:
1 name_list = ['alex', 'seven', 'eric'] 2 或 3 name_list = list(['alex', 'seven', 'eric'])
基本操作:
- 索引
- name_list[0] #取一个,原来是什么类型元素,还是什么类型
切片
-
name_list[0:2] #取出来多个元素,放到一个集合中是列表。name_list[2:len(name_list):2] 步长,步长-1时翻转
-
#追加,在原有基础后面添加list.append()
- 扩展,extend
- 插入,insert
- 删除
- pop,remove,clear,del
- 长度
- len(name_list)
- 循环
-
for item in name_list:print item
-
- 包含
-
if item in name_listreturn
-
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 """ 添加 元素 8 L.append(object) -> None -- append object to end """ 9 pass 10 11 def clear(self): # real signature unknown; restored from __doc__ 12 """ 清空元素 13 L.clear() -> None -- remove all items from L """ 14 pass 15 16 def copy(self): # real signature unknown; restored from __doc__ 17 """ 浅copy L.copy() -> list -- a shallow copy of L """ 18 return [] 19 20 def count(self, value): # real signature unknown; restored from __doc__ 21 """ 匹配 value的个数 L.count(value) -> integer -- return number of occurrences of value """ 22 return 0 23 24 def extend(self, iterable): # real signature unknown; restored from __doc__ 25 """ 拼接两个列表 L.extend(iterable) -> None -- extend list by appending elements from the iterable """ 26 pass 27 28 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 29 """ 返回 某个value 的索引 30 L.index(value, [start, [stop]]) -> integer -- return first index of value. 31 Raises ValueError if the value is not present. 32 """ 33 return 0 34 35 def insert(self, index, p_object): # real signature unknown; restored from __doc__ 36 """ 指定索引位置处添加元素 L.insert(index, object) -- insert object before index """ 37 pass 38 39 def pop(self, index=None): # real signature unknown; restored from __doc__ 40 """ 删除结尾的元素 41 L.pop([index]) -> item -- remove and return item at index (default last). 42 Raises IndexError if list is empty or index is out of range. 43 """ 44 pass 45 46 def remove(self, value): # real signature unknown; restored from __doc__ 47 """ 移除 从左测匹配的第一个元素 48 L.remove(value) -> None -- remove first occurrence of value. 49 Raises ValueError if the value is not present. 50 """ 51 pass 52 53 def reverse(self): # real signature unknown; restored from __doc__ 54 """ 反转列表 L.reverse() -- reverse *IN PLACE* """ 55 pass 56 57 def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__ 58 """ 排序 但是int str不行 L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ 59 pass 60 61 def __add__(self, *args, **kwargs): # real signature unknown 62 """ Return self+value. """ 63 pass 64 65 def __contains__(self, *args, **kwargs): # real signature unknown 66 """ Return key in self. """ 67 pass 68 69 def __delitem__(self, *args, **kwargs): # real signature unknown 70 """ Delete self[key]. """ 71 pass 72 73 def __eq__(self, *args, **kwargs): # real signature unknown 74 """ Return self==value. """ 75 pass 76 77 def __getattribute__(self, *args, **kwargs): # real signature unknown 78 """ Return getattr(self, name). """ 79 pass 80 81 def __getitem__(self, y): # real signature unknown; restored from __doc__ 82 """ x.__getitem__(y) <==> x[y] """ 83 pass 84 85 def __ge__(self, *args, **kwargs): # real signature unknown 86 """ Return self>=value. """ 87 pass 88 89 def __gt__(self, *args, **kwargs): # real signature unknown 90 """ Return self>value. """ 91 pass 92 93 def __iadd__(self, *args, **kwargs): # real signature unknown 94 """ Implement self+=value. """ 95 pass 96 97 def __imul__(self, *args, **kwargs): # real signature unknown 98 """ Implement self*=value. """ 99 pass 100 101 def __init__(self, seq=()): # known special case of list.__init__ 102 """ 103 list() -> new empty list 104 list(iterable) -> new list initialized from iterable's items 105 # (copied from class doc) 106 """ 107 pass 108 109 def __iter__(self, *args, **kwargs): # real signature unknown 110 """ Implement iter(self). """ 111 pass 112 113 def __len__(self, *args, **kwargs): # real signature unknown 114 """ Return len(self). """ 115 pass 116 117 def __le__(self, *args, **kwargs): # real signature unknown 118 """ Return self<=value. """ 119 pass 120 121 def __lt__(self, *args, **kwargs): # real signature unknown 122 """ Return self<value. """ 123 pass 124 125 def __mul__(self, *args, **kwargs): # real signature unknown 126 """ Return self*value.n """ 127 pass 128 129 @staticmethod # known case of __new__ 130 def __new__(*args, **kwargs): # real signature unknown 131 """ Create and return a new object. See help(type) for accurate signature. """ 132 pass 133 134 def __ne__(self, *args, **kwargs): # real signature unknown 135 """ Return self!=value. """ 136 pass 137 138 def __repr__(self, *args, **kwargs): # real signature unknown 139 """ Return repr(self). """ 140 pass 141 142 def __reversed__(self): # real signature unknown; restored from __doc__ 143 """ L.__reversed__() -- return a reverse iterator over the list """ 144 pass 145 146 def __rmul__(self, *args, **kwargs): # real signature unknown 147 """ Return self*value. """ 148 pass 149 150 def __setitem__(self, *args, **kwargs): # real signature unknown 151 """ Set self[key] to value. """ 152 pass 153 154 def __sizeof__(self): # real signature unknown; restored from __doc__ 155 """ L.__sizeof__() -- size of L in memory, in bytes """ 156 pass 157 158 __hash__ = None
示例:
1 ###### 列表 ########## 2 3 #!/usr/bin/env python 4 # _*_ coding:utf-8 _*_ 5 6 7 lis=[1,2,3,'alex'] 8 cc=[5,5] 9 print(lis.count("alex")) 10 lis.extend(cc) 11 print(lis) 12 13 name_list = ["eirc", "alex", 'tony'] 14 """ 15 # 索引 16 print(name_list[0]) 17 # 切片 18 print(name_list[0:2]) 19 # len 20 print(name_list[2:len(name_list)]) 21 # for 22 for i in name_list: 23 print(i) 24 25 26 #join 方法,拼接字符串 27 li = ["alex","eric"] 28 name = "li jie" 29 ss = "_".join(li) 30 s = "_".join(name) 31 print(s,ss) 32 33 34 """ 35 # 列表内部提供的其他功能 36 # append后追加 37 name_list.append('seven') 38 name_list.append('seven') 39 name_list.append('seven') 40 print(name_list) 41 # 元素出现的次数 42 print(name_list.count('seven')) 43 # iterable,可迭代的 44 temp = [111,22,33,44] 45 # 扩展,批量添加 46 name_list.extend(temp) 47 print(name_list) 48 # 获取指定元素的索引位置 49 print(name_list.index('alex')) 50 # 向指定索引位置插入数据 51 name_list.insert(1, 'SB') 52 print(name_list) 53 # 在原列表中移除掉最后一个元素,并将其赋值给 a1 54 a1 = name_list.pop() 55 print(name_list) 56 print(a1) 57 # 移除某个元素 58 name_list.remove('seven') 59 print(name_list) 60 # 翻转 61 name_list.reverse() 62 print(name_list) 63 64 # 删除指定索引位置 65 print(name_list) 66 del name_list[1:3] 67 print(name_list)
列表练习:
# list列表方法练习 name_list = ['alex', 'seven', 'eric'] #增加 name_list.append("seven") # 在末尾追加 name_list.append("seven") print(name_list) temp = [11, "bb", 222] name_list.extend(temp) # 本身后面添加可迭代的参数, print(name_list) name_list.extend("abc") # 本身后面添加可迭代的参数 print(name_list) name_list.insert(1, "sb") # 在某个位置插入 print(name_list) #查找 print(name_list.count("seven")) # 统计出现的次数 # iterable可迭代的,只要能够通过for循环的 都是可迭代的。 print(name_list.index(11)) # 索引,查位置,参数:str,start,end。可以添加索引范围的。 #删除 del name_list[1] #直接del删除,索引擅长,超出报错 print(name_list) a = name_list.pop() # 默认尾部删掉,可赋值给别人,如果删完了会报错 print(name_list, a) a = name_list.pop(2) #索引删除并赋值,如果超出索引报错 print(name_list, a) x = name_list.remove("seven") # 只移除找到的第一个,不可赋值,找不到时报错 print(name_list, x) #x是None,无法赋值 # name_list.clear() #直接清空 name_list4 = ["eirc", "andy", "ALex"] del name_list4[1] # 删除列表指定位置的元素,索引位置,可用切片 print(name_list4) # 反转 name_list.reverse() #列表翻转 print(name_list) # 排序,里面的元素类型必须一致 name_list2 = [1, 2, 44, 52, 4, 2, 55, 2] name_list3 = ["kksaj", "jalkdjl", "ax", "bb"] name_list3.sort() print(name_list3)
#join 方法,拼接字符串
1 #join 方法,拼接字符串 2 li = ["alex","eric"] 3 name = "li jie" 4 ss = "_".join(li) 5 s = "_".join(name) 6 print(s,ss)
join是从可迭代的元素第一个元素后面开始拼接,在其他元素前面加上“ ”中的元素进行拼接
print("_".join(["abc","ef"])) print("_".join("alex li")) abc_ef a_l_e_x_ _l_i
5、元祖
创建元祖: 元组一旦创建 不等增加也不能减少
- 索引
-
name_list[0]
-
- 切片
-
name_list[0:2]name_list[2:len(name_list):2]步长
-
- 循环
-
for item in name_list:print item
-
- 长度
-
len(name_list)
-
- 包含
- in
1 class tuple(object): 2 """ 3 tuple() -> empty tuple 4 tuple(iterable) -> tuple initialized from iterable's items 5 6 If the argument is a tuple, the return value is the same object. 7 """ 8 def count(self, value): # real signature unknown; restored from __doc__ 9 """ 计算 value的个数 T.count(value) -> integer -- return number of occurrences of value """ 10 return 0 11 12 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 13 """ 索引 14 T.index(value, [start, [stop]]) -> integer -- return first index of value. 15 Raises ValueError if the value is not present. 16 """ 17 return 0 18 19 def __add__(self, *args, **kwargs): # real signature unknown 20 """ Return self+value. """ 21 pass 22 23 def __contains__(self, *args, **kwargs): # real signature unknown 24 """ Return key in self. """ 25 pass 26 27 def __eq__(self, *args, **kwargs): # real signature unknown 28 """ Return self==value. """ 29 pass 30 31 def __getattribute__(self, *args, **kwargs): # real signature unknown 32 """ Return getattr(self, name). """ 33 pass 34 35 def __getitem__(self, *args, **kwargs): # real signature unknown 36 """ Return self[key]. """ 37 pass 38 39 def __getnewargs__(self, *args, **kwargs): # real signature unknown 40 pass 41 42 def __ge__(self, *args, **kwargs): # real signature unknown 43 """ Return self>=value. """ 44 pass 45 46 def __gt__(self, *args, **kwargs): # real signature unknown 47 """ Return self>value. """ 48 pass 49 50 def __hash__(self, *args, **kwargs): # real signature unknown 51 """ Return hash(self). """ 52 pass 53 54 def __init__(self, seq=()): # known special case of tuple.__init__ 55 """ 56 tuple() -> empty tuple 57 tuple(iterable) -> tuple initialized from iterable's items 58 59 If the argument is a tuple, the return value is the same object. 60 # (copied from class doc) 61 """ 62 pass 63 64 def __iter__(self, *args, **kwargs): # real signature unknown 65 """ Implement iter(self). """ 66 pass 67 68 def __len__(self, *args, **kwargs): # real signature unknown 69 """ Return len(self). """ 70 pass 71 72 def __le__(self, *args, **kwargs): # real signature unknown 73 """ Return self<=value. """ 74 pass 75 76 def __lt__(self, *args, **kwargs): # real signature unknown 77 """ Return self<value. """ 78 pass 79 80 def __mul__(self, *args, **kwargs): # real signature unknown 81 """ Return self*value.n """ 82 pass 83 84 @staticmethod # known case of __new__ 85 def __new__(*args, **kwargs): # real signature unknown 86 """ Create and return a new object. See help(type) for accurate signature. """ 87 pass 88 89 def __ne__(self, *args, **kwargs): # real signature unknown 90 """ Return self!=value. """ 91 pass 92 93 def __repr__(self, *args, **kwargs): # real signature unknown 94 """ Return repr(self). """ 95 pass 96 97 def __rmul__(self, *args, **kwargs): # real signature unknown 98 """ Return self*value. """ 99 pass
示例:
1 ############### 元组 ################# 2 name_tuple = ('alex', 'eric') 3 # 索引 4 print(name_tuple[0]) 5 # len 6 print(name_tuple[len(name_tuple)-1]) 7 # 切片 8 print(name_tuple[0:1]) 9 # for 10 for i in name_tuple: 11 print(i) 12 # 删除 13 # del name_tuple[0] 不支持 14 # count,计算元素出现的个数 15 print(name_tuple.count('alex')) 16 # index 获取指定元素的索引位置 17 print(name_tuple.index('alex'))
示例练习:
#!/usr/bin/env python # -*- coding:utf-8 -*- # tuple元祖的特殊方法练习 name_list = ('alex', 'seven', 'eric', "alex") print(name_list.index("alex")) # 获取指定元素的索引编号 print(name_list.count("alex")) # 获取指定元素的个数 # tuple(列表)列表变元组 a = range(10) print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] d = tuple(a) print(d) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # list(元组)元组变列表 print(d) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) e = list(a) print(e) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #有些时候我们的列表数据不想被人修改时怎么办? 就可以用元组存放,元组又被称为只读列表,不能修改。 # 定义:与列表类似,只不过[]改成(),很多用法和list一致, # 注意:元组本身不可变,如果元组中还包含其他可变元素,这些可变元素可以改变 data = (99, 88, 77, ['Alex', 'Jack'], 33) data[3][0] = '金角大王' print(data) # (99, 88, 77, ['金角大王', 'Jack'], 33) # 为啥呢? 因为元组只是存每个元素的内存地址,上面[‘金角大王’, ‘Jack’]这个列表本身的内存地址存在元组里确实不可变,但是这个列表包含的元素的内存地址是存在另外一块空间里的,是可变的。
6、字典(无序)
创建字典:
1 user_info={"name":"alex", 2 "age":18, 3 "gender":"M", 4 }
1 li=["kk","jkjkj","sdfj"] 2 new_dict=dict(enumerate(li)) 3 print new_dict #{0: 'kk', 1: 'jkjkj', 2: 'sdfj'}
创建操作 >>>person = {"name": "alex", 'age': 20} #或 >>>person = dict(name='seven', age=20) #或 >>>person = dict({"name": "egon", 'age': 20}) #或 >>> {}.fromkeys([1,2,3,4,5,6,7,8],100) {1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100, 7: 100, 8: 100} 增加操作 names = { "alex": [23, "CEO", 66000], "黑姑娘": [24, "行政", 4000], } # 新增k names["佩奇"] = [26, "讲师", 40000] names.setdefault("oldboy",[50,"boss",100000]) # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D 删除操作 names.pop("alex") # 删除指定key names.popitem() # 随便删除1个key del names["oldboy"] # 删除指定key,同pop方法 names.clear() # 清空dict 修改操作 dic['key'] = 'new_value',如果key在字典中存在,'new_value'将会替代原来的value值; dic.update(dic2) 将字典dic2的键值对添加到字典dic中,如果有重复的key,这更新value值 查操作 dic['key'] #返回字典中key对应的值,若key不存在字典中,则报错; dic.get(key, default = None)#返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None) 'key' in dic #若存在则返回True,没有则返回False dic.keys() 返回一个包含字典所有KEY的列表; dic.values() 返回一个包含字典所有value的列表; dic.items() 返回一个包含所有(键,值)元组的列表; 循环 1、for k in dic.keys() 2、for k,v in dic.items() 3、for k in dic # 推荐用这种,效率速度最快 info = { "name":"小猿圈", "mission": "帮一千万极客高效学编程", "website": "http://apeland.com" } for k in info: print(k,info[k]) 输出 name 小猿圈 mission 帮一千万极客高效学编程 website http://apeland.com 求长度 len(dic)
常用操作:
- 索引
-
print user_info["name"]print user_info["age"]
-
- 新增
- 直接添加user_info["新的键"]="新的值"
- user_info.update({"kkk":"xxx"})
- 删除
- pop
- 键、值、键值对
- 循环
-
1 for item in user_info: #默认输出的是keys 2 print item 3 for item in user_info.values: #获取所有的值 4 print item 5 for i j in user_info.items: #获取所有的键值对 6 print i,j 7 user_info.keys() #获取所有的key 8 user_info.values() #获取所有的值 9 user_info.items() #获取所有的键值对
-
- 长度
- len(user_info)
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 def clear(self): # real signature unknown; restored from __doc__ 14 """ 清除 字典 D.clear() -> None. Remove all items from D. """ 15 pass 16 17 def copy(self): # real signature unknown; restored from __doc__ 18 """ 浅拷贝 D.copy() -> a shallow copy of D """ 19 pass 20 21 @staticmethod # known case 22 def fromkeys(*args, **kwargs): # real signature unknown 23 """ Returns a new dict with keys from iterable and values equal to value. """ 24 pass 25 26 def get(self, k, d=None): # real signature unknown; restored from __doc__ 27 """ 根据key获取 d是默认是 为 None D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 28 pass 29 30 def items(self): # real signature unknown; restored from __doc__ 31 """ 将字典的key value都打印成列表元组 D.items() -> a set-like object providing a view on D's items """ 32 pass 33 34 def keys(self): # real signature unknown; restored from __doc__ 35 """打印字典的key D.keys() -> a set-like object providing a view on D's keys """ 36 pass 37 38 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 39 """ 获取并在字典中移除 40 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 41 If key is not found, d is returned if given, otherwise KeyError is raised 42 """ 43 pass 44 45 def popitem(self): # real signature unknown; restored from __doc__ 46 """ 获取并在列表中移除 47 D.popitem() -> (k, v), remove and return some (key, value) pair as a 48 2-tuple; but raise KeyError if D is empty. 49 """ 50 pass 51 52 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 53 """如果key不存在,则创建,如果存在,则返回已存在的值且不修改 54 55 D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 56 pass 57 58 def update(self, E=None, **F): # known special case of dict.update 59 """ 60 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 61 If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] 62 If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v 63 In either case, this is followed by: for k in F: D[k] = F[k] 64 """ 65 pass 66 67 def values(self): # real signature unknown; restored from __doc__ 68 """ 所有的值 D.values() -> an object providing a view on D's values """ 69 pass 70 71 def __contains__(self, *args, **kwargs): # real signature unknown 72 """ True if D has a key k, else False. """ 73 pass 74 75 def __delitem__(self, *args, **kwargs): # real signature unknown 76 """ Delete self[key]. """ 77 pass 78 79 def __eq__(self, *args, **kwargs): # real signature unknown 80 """ Return self==value. """ 81 pass 82 83 def __getattribute__(self, *args, **kwargs): # real signature unknown 84 """ Return getattr(self, name). """ 85 pass 86 87 def __getitem__(self, y): # real signature unknown; restored from __doc__ 88 """ x.__getitem__(y) <==> x[y] """ 89 pass 90 91 def __ge__(self, *args, **kwargs): # real signature unknown 92 """ Return self>=value. """ 93 pass 94 95 def __gt__(self, *args, **kwargs): # real signature unknown 96 """ Return self>value. """ 97 pass 98 99 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 100 """ 101 dict() -> new empty dictionary 102 dict(mapping) -> new dictionary initialized from a mapping object's 103 (key, value) pairs 104 dict(iterable) -> new dictionary initialized as if via: 105 d = {} 106 for k, v in iterable: 107 d[k] = v 108 dict(**kwargs) -> new dictionary initialized with the name=value pairs 109 in the keyword argument list. For example: dict(one=1, two=2) 110 # (copied from class doc) 111 """ 112 pass 113 114 def __iter__(self, *args, **kwargs): # real signature unknown 115 """ Implement iter(self). """ 116 pass 117 118 def __len__(self, *args, **kwargs): # real signature unknown 119 """ Return len(self). """ 120 pass 121 122 def __le__(self, *args, **kwargs): # real signature unknown 123 """ Return self<=value. """ 124 pass 125 126 def __lt__(self, *args, **kwargs): # real signature unknown 127 """ Return self<value. """ 128 pass 129 130 @staticmethod # known case of __new__ 131 def __new__(*args, **kwargs): # real signature unknown 132 """ Create and return a new object. See help(type) for accurate signature. """ 133 pass 134 135 def __ne__(self, *args, **kwargs): # real signature unknown 136 """ Return self!=value. """ 137 pass 138 139 def __repr__(self, *args, **kwargs): # real signature unknown 140 """ Return repr(self). """ 141 pass 142 143 def __setitem__(self, *args, **kwargs): # real signature unknown 144 """ Set self[key] to value. """ 145 pass 146 147 def __sizeof__(self): # real signature unknown; restored from __doc__ 148 """ D.__sizeof__() -> size of D in memory, in bytes """ 149 pass 150 151 __hash__ = None
示例:
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 4 5 6 dic={1:2,"alex":4,4:9} 7 print(dic.get("alex")) 8 print(dic.items()) 9 print(dic.keys()) 10 print(dic.values()) 11 print(dic.pop(2,None)) 12 print(dic.setdefault("name","rain")) 13 14 ###################### 字典 ################### 15 # 字典的每一个元素,键值对 16 user_info = { 17 0: "alex", 18 "age": 73, 19 2: 'M' 20 } 21 # 0 “alex" 22 # 1 73 23 24 # 索引 25 # print(user_info[0]) 26 # print(user_info["age"]) 27 28 # 循环,默认值输出key 29 # for i in user_info: 30 # print(i) 31 32 # # 获取所有键 33 # print(user_info.keys()) 34 # # 获取所有值 35 # print(user_info.values()) 36 # # 获取所有键值对 37 # print(user_info.items()) 38 39 # for i in user_info.keys(): 40 # print(i) 41 # 42 # for i in user_info.values(): 43 # print(i) 44 45 # user_info = { 46 # 0: "alex", 47 # "age": 73, 48 # 2: 'M' 49 # } 50 # for k,v in user_info.items(): 51 # print(k) 52 # print(v) 53 54 # clear,清除所有内容 55 # user_info.clear() 56 # print(user_info) 57 58 # get 根据key获取值,如果key不存在,可以指定一个默认值 59 # val = user_info.get('age') 60 # print(val) 61 # val = user_info.get('age', '123') 62 # print(val) 63 # 索引取值时,key不存在,报错 64 # print(user_info['age']) 65 # print(user_info['age1111']) 66 67 68 69 # has_key 检查字典中指定key是否存在 3版本python没有了 可以用in 判断 70 # ret = 'agfffe' in user_info.keys() 71 # print(ret) 72 # pop 73 74 # popitem 75 76 # update 77 # print(user_info) 78 # test = { 79 # "a1": 123, 80 # 'a2': 456 81 # } 82 # user_info.update(test) 83 # print(user_info) 84 85 # 删除指定索引的键值对 86 test = { 87 "a1": 123, 88 'a2': 456 89 } 90 91 del test['a1'] 92 print(test)
示例练习:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #dict字典的特殊方法 4 5 user_info={"name":"alex", 6 "age":18, 7 "gender":"M" 8 } 9 print len(user_info)#长度 10 #user_info.clear()#清空字典,清楚所有内容 11 print user_info.get("name") 12 print user_info.get("name1",123) # """ 根据key获取值,d是默认值 """如果key不存在,返回默认值,不会报错 13 print user_info["name"] #如果不存在会报错 14 print user_info.has_key("name") #""" 是否有key """ 15 a=user_info.pop("age")#获取并在字典中移除,可以将key赋值给一个变量 16 print user_info,a 17 a=user_info.popitem()#移除key values 赋值给一个元祖中 18 print user_info, 19 20 user_info.iteritems() 21 print user_info 22 user_info.update({"kkk":"jjk"})#更新 23 print user_info 24 25 #@staticmethod,类方法 26 user_info_new=dict.fromkeys(["k","name"],"alex") 27 print user_info_new
1 2版本python 查看字典有没有这个key 2 >>> contact['4343'] 3 Traceback (most recent call last): 4 File "<stdin>", line 1, in <module> 5 KeyError: '4343' 6 >>> contact.has_key('343') 7 False 8 >>> contact.has_key('3333') 9 True 10 清空字典contact.clear() 11 >>> contact.clear()
5、for循环
1 li = [11,22,33] 2 for i in li: 3 print(li.index(i),i)
6、enumrate
为可迭代的对象添加序号
1 li = [11,22,33] 2 for k,v in enumerate(li, 1): 3 print(k,v)
7、range 和xrange
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] 9 10 例如 : 11 print(range(1,10)) 12 没有循环,因此输出 range(1, 10) 而不是1 2 3.。。10 13
8、练习题
1、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于等于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 lis=[11,22,33,44,55,66,77,88,99,90] 4 dic={"k1":[],"k2":[]} 5 for i in lis: 6 if i>66: 7 dic["k1"].append(i) 8 else: 9 dic["k2"].append(i) 10 print dic
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 li = ["alec", " Aric", "Alei", "Tony", "rain"] 4 tu = ("alec", " Aric", "Alei", "Tony", "rain") 5 dic = {'k1': "alei", 'k2': ' aric', "k3": "Alec", "k4": "Tony"} 6 li_new = [] 7 tu_new = [] 8 dic_new={} 9 for i in li: 10 i=i.strip() 11 #if判断顺序,从前往后,or,自己成功就行了,and。 12 if (i.startswith("a") or i.startswith("A")) and i.endswith("c"): 13 li_new.append(i) 14 else: 15 pass 16 for i in tu: 17 i=i.strip() 18 if (i.startswith("a") or i.startswith("A")) and i.endswith("c"): 19 tu_new.append(i) 20 else: 21 pass 22 for i,j in dic.items(): 23 j=j.strip() 24 if (j.startswith("a") or j.startswith("A")) and j.endswith("c"): 25 # dic_new.update({i:j}) 26 dic_new[i]=j 27 else: 28 pass 29 print li_new 30 print tu_new 31 print dic_new
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 li=["手机", "电脑", '鼠标垫', '游艇'] 4 for i,j in enumerate(li,1): 5 print i,j 6 inp=int(raw_input("请选择:")) 7 print li[inp-1]
功能要求:
- 要求用户输入总资产,例如:2000
- 显示商品列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
- 附加:可充值、某商品移除购物车
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 goods = [ 4 {"name": "电脑", "price": 1999}, 5 {"name": "鼠标", "price": 10}, 6 {"name": "游艇", "price": 20}, 7 {"name": "美女", "price": 998}, 8 ] 9 glod=int(input("您的总资产为:")) 10 def show_goods(): 11 for i in goods: 12 print(str(goods.index(i)) + ":" + i["name"], i["price"], "元") 13 print("4:结算") 14 def show_gwc(): 15 for item in gwc.items(): 16 print(item[0], "数量:" + str(item[1]["数量"]), "单价:" + str(item[1]["单价"])) 17 total=0 18 gwc={} 19 show_goods() 20 while True: 21 get_goods=int(input("请输入你要购买的商品编号,结算请输入4:")) 22 if get_goods<3: 23 if goods[get_goods]["name"] in gwc.keys(): 24 gwc[goods[get_goods]["name"]]["数量"]+=1 25 else: 26 gwc[goods[get_goods]["name"]] = {"数量": 1, "单价": goods[get_goods]["price"]} 27 total = total + goods[get_goods]["price"] 28 show_gwc() 29 show_goods() 30 continue 31 elif get_goods>4: 32 print("输入错误") 33 show_goods() 34 continue 35 else: 36 if total<=glod: 37 print("你购买的商品总额为%d元,购买成功" % total) 38 else: 39 print("余额不足") 40 break