编码转换:
示例:
#这是python2.7中
#_*_ coding:utf-8 _*_
temp = "你好,世界" # utf-8
#解码,需要指定原来是什么编码
temp_unicode = temp.decode("utf-8")
#编码,需要指定原来是什么编码
temp_gbk = temp_unicode.encode("gbk")
print(temp_gbk)
#在python 3中
temp = "你好,世界"
temp_gbk = temp.encode("gbk")
print(temp_gbk)
运算符
1,算数运算:
假设变量a持有10和变量b持有20,则:
运算符 | 描述 | 实例 |
+ | 加法 - 对操作符的两侧加值 | a + b = 30 |
- | 减法 - 从左侧操作数减去右侧操作数 | a - b = -10 |
* | 乘法- 相乘运算符两侧的值 | a * b= 200 |
/ | 除 - 由右侧操作数除以左侧操作数 | b / a = 2 |
% | 模 - 由右侧操作数和余返回除以左侧操作数 | b % = 0 |
** | 指数- 执行对操作指数(幂)的计算 | a**b = 10 幂为 20 |
// | 地板除 - 操作数的除法,其中结果是将小数点后的位数被除去的商。 | 9//2 = 4 而 9.0//2.0= 4.0 |
实例:
#!/usr/bin/python
a = 20
b = 10
c = 0
c = a + b
print "w1 ", c
c = a - b
print "w2 ", c
c = a * b
print "w3 ", c
c = a / b
print "w4 ", c
c = a % b
print "w5 ", c
a = 2
b = 3
c = a**b
print "w6 ", c
a = 10
b = 5
c = a//b
print "w7 ", c
运算结果:
w1 30
w2 10
w3 200
w4 2
w5 0
w6 8
w7 2
2,比较运算
假设变量a持有10和变量b持有20,则:
运算符 | 描述 | 示例 |
== | 检查两个操作数的值是否相等,如果是,则条件变为真。 | (a == b) 不为 true. |
!= | 检查两个操作数的值是否等相等,如果值不相等,则条件变为真。 | (a != b) 为 true. |
<> | 检查两个操作数的值是否等相等,如果值不相等,则条件变为真。 | (a <> b) 结果为true。这类似于!=运算符。 |
> | 检查左操作数的值是否大于右操作数的值,如果是,则条件成立。 | (a > b) 为 true. |
< | 检查左操作数的值是否小于右操作数的值,如果是,则条件成立。 | (a < b) 为true. |
>= | 检查左操作数的值是否大于或等于右操作数的值,如果是,则条件成立。 | (a >= b) 不为 true. |
<= | 检查左操作数的值是否小于或等于右操作数的值,如果是,则条件成立。 | (a <= b) 为 true. |
实例:
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 a = 20 5 b = 10 6 c = 0 7 8 if ( a == b ): 9 print "e1 等于 b" 10 else: 11 print "e1 不等于 b" 12 13 if ( a != b ): 14 print "e2 不等于 b" 15 else: 16 print "e2 等于 b" 17 18 if ( a <> b ): 19 print "e3 不等于 b" 20 else: 21 print "e3 等于 b" 22 23 if ( a < b ): 24 print "e4 小于 b" 25 else: 26 print "e4 大于等于 b" 27 28 if ( a > b ): 29 print "e5 大于 b" 30 else: 31 print "e5 小于等于 b" 32 33 34 if ( a <= b ): 35 print "e6 小于等于 b" 36 else: 37 print "e6 大于 b" 38 39 if ( b >= a ): 40 print "e7 大于等于 b" 41 else: 42 print "e7 小于 b" 43 44 运算结果: e1 不等于 b e2 不等于 b e3 不等于 b e4 大于等于 b e5 大于 b e6 大于 b e7 小于 b
3,赋值运算
运算符 | 描述 | 示例 |
= | 简单的赋值运算符,赋值从右侧操作数左侧操作数 | c = a + b 类似于 a + b 到 c |
+= | 添加和赋值操作符,它增加了右操作数左操作数和结果赋给左操作数 | c += a 类似于 c = c + a |
-= | 减和赋值操作符,它减去右边的操作数从左边操作数,并将结果赋给左操作数 | c -= a 类似于 c = c - a |
*= | 乘法和赋值操作符,它乘以右边的操作数与左操作数,并将结果赋给左操作数 | c *= a 类似于 c = c * a |
/= | 除和赋值操作符,它把左操作数与正确的操作数,并将结果赋给左操作数 | c /= a 类似于 c = c / a |
%= | 模量和赋值操作符,它需要使用两个操作数模和结果赋给左操作数 | c %= a 类似于 c = c % a |
**= | 指数和赋值运算符,执行指数(幂)计算操作符和赋值给左操作数 | c **= a 类似于 c = c ** a |
//= | 地板除,并分配一个值,执行地板划分对操作和指定值到左操作数 | c //= a 类似于 c = c // a |
实例:
#!/usr/bin/python # -*- coding: UTF-8 -*-
a = 20
b = 10
c = 0
c = a + b
print "q1的值为:", c
c += a
print "q2的值为:", c
c *= a
print "q3的值为:", c
c /= a
print "q4的值为:", c
c = 2
c %= a
print "q5的值为:", c
c **= a
print "q6的值为:", c
c //= a
print "q7的值为:", c
运算结果:
q1的值为: 30
q2的值为: 50
q3的值为: 1000
q4的值为: 50
q5的值为: 2
q6的值为: 1048576
q7的值为: 52428
4,逻辑运算
假设变量a持有10和变量b持有20:
运算符 |
描述 | 例子 |
and | 所谓逻辑与运算符。如果两个操作数都为真,则条件为真。 | (a and b) 为 true. |
or | 所谓逻辑OR运算符。如果有两个操作数都为非零,则条件变为真。 | (a or b) 为 true. |
not | 所谓逻辑非运算符。用反转操作数的逻辑状态。如果条件为true,则逻辑非运算符将为false。 | not(a and b) 为 false. |
实例:
a = 10 b = 20 if ( a and b ): print " a 和 b 都为 true" else: print " a 和 b 有一个不为 true" if ( a or b ): print " a 和 b 都为 true,或其中一个变量为 true" else: print " a 和 b 都不为 true" # 修改变量 a 的值 a = 0 if ( a and b ): print " a 和 b 都为 true" else: print " a 和 b 有一个不为 true" if ( a or b ): print " a 和 b 都为 true,或其中一个变量为 true" else: print " a 和 b 都不为 true" if not( a and b ): print " a 和 b 都为 false,或其中一个变量为 false" else: print " a 和 b 都为 true"
运算结果:
a 和 b 都为 true
a 和 b 都为 true,或其中一个变量为 true
a 和 b 有一个不为 true
a 和 b 都为 true,或其中一个变量为 true
a 和 b 都为 false,或其中一个变量为 false
5,成员运算
运算符 | 描述 | 实例 |
in | 如果在指定的序列中找到值返回 True,否则返回 False。 | x 在 y 序列中 , 如果 x 在 y 序列中返回 True。 |
not in | 如果在指定的序列中没有找到值返回 True,否则返回 False。 | x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。 |
实例:
#!/usr/bin/python # -*- coding: UTF-8 -*- a = 10 b = 20 list = [1, 2, 3, 4, 5 ]; if ( a in list ): print "a 在给定的列表中 list 中" else: print "a 不在给定的列表中 list 中" if ( b not in list ): print "b 不在给定的列表中 list 中" else: print "b 在给定的列表中 list 中" # 修改变量 a 的值 a = 2 if ( a in list ): print "a 在给定的列表中 list 中" else: print "a 不在给定的列表中 list 中"
运算结果:
a 不在给定的列表中 list 中
b 不在给定的列表中 list 中
a 在给定的列表中 list 中
Pychorm 的设置
1,模板
file => settings =>Editor => file and code template => python script =>右上方 #!/usr/bin/env python # _*_ coding:utf-8 _*_ 按OK确定
2,文字大小
file => settings =>Editor => color and font =>font =>save as ... =>14
3,运行(3种方法)
a,点击运行文件,右键 rum
b,view => tooldar
选中要执行的文件
点击 运行
c,在当前文件空白处,右键,rum
4,切换py版本
file => settings =>project interpreter => 选择版本
基本数据类型
1,数字
整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。
1, n1 = 123 n2 = 456 print(n1 + n2) #print(n1._add_(n2)) 这是内部执行的 2, n1 = 4 ret = n1.bit_length() #获取数字在二进制中的最短位数 print(ret)
2,字符串(str)
1,capitalize 首字母变大写
示例: a1 = "alex" ret = a1.capitalize() print(ret) 2,center 让字符串居中
示例: a1 = "alex" a1.center(10,"*") print(ret) 3,count 在子 字符串中出现几个 a1 = "alex is alph" ret = a1.count("a1") print(ret) a1 = "alex is alph" ret = a1.count("a1",0,8) print(ret) 4,endswith 是否以什么结尾 示例:
temp = "hello" print(temp.endswith("o")) 5,expandtads 一个tab换成8个空格 示例:
content = ("hello\t999") print(content.expandtads()) print(content.expandtads(20)) 6,find 能找到就到那个位子,没找到就返回一个-1 示例:
s = "alex hello" print(s.find("p") 7,format 字符串的格式化 示例:
s = "hello {0}, age {1}" print(s) # {0} 占位符 new1 = s.format("alex", 19) print(new1) 运算结果: hello {0}, age {1} hello alex, age 19 8,index获取子序列的位子,如果没找到就报错 示例:
s = "alex hello" print(s.index("p") 9,isalnum 判断字符串是否是字母和数字 #接self表示不用添加参数 示例:
a = "alex5" a.isalnum()
10,isalpha 是否是字母
11,iadigit 是否是数字 12,islower 是否是小写
13,title 变成标题 示例:
s = "the schol" ret = s.title() print(ret) 运算结果: The School 14,istitle 是否是标题
15,isupper 检验是否全部是大写 16,join 用**连接 示例:
li = ["alex", "eric"] #中括号表示列表类型 s = "**".join(li) print(s) li = ("alex", "eric") #小括号表示元祖类型 s = "**".join(li) print(s) 17,ljust 内容左对齐,右侧填充
18,rjust 内容右对齐,左侧填充
19,lstrip 移除左边的空格 示例:
s =" alex " news = s.lstrip() print(news) 20,strip 移除两边空白 rstrip 移除右边的空格 示例:
s =" alex " news = s.rstrip() print(news) 21,partition 从左找 ,分割,前,中,后三部分 示例:
s = " hello is world " ret = s.partition('is') print(ret)
22,rpartition 从右找,分割,前,中,后三部分
23,replace 表示替换 示例:
s = " hello is world " ret = s.replace('l','a') print(ret) s = " hello is world " ret = s.replace('l','a',2) #从左起到第二个 print(ret)
24,rsplit 从右找 分割
25,split 从左找 分割
示例:
s = "alexalexalex"
ret = s.split("e")
print(ret)
运算结果:
['al', 'xal', 'xal', 'x']
s = "alexalexalex"
ret = s.split("e",2)
print(ret)
运算结果:
['al', 'xal', 'xalex']
26,splitlines 根据换行分割
27,startswith 是否以某个字符串开始
28,swapcase 大写变小写,小写变大写
示例:
s = "aLeX"
print(s.swapcase())
运算结果:
AlEx
29,upper 变大写
基本操作:
1,索引
示例: s = "hello" print(s[0]) print(s[1]) print(s[2]) print(s[3]) print(s[4]) ret = len(s) #len 表示有几个字符串 print(ret) 运算结果: h e l l o 5
2,长度
#len 表示有几个字符串 示例:
s = "hello" ret = len(s) print(ret) 运算结果: 5
3,切片
切片
示例:
s = "hello" print(s[0:2]) 运算结果: he
4,循环
#while循环 示例:
s = "hello" start = 0 while start <len(s): temp = s[start] print(temp) start +=1 运算结果: h e l l o #for循环 #continue,break在for循环中一样适用 示例:
s = "hello" for item in s: #item变量名 print(item) 运算结果: h e l l o s = "hello" for item in s: if item =="l": continue print(item) 运算结果: h e o s = "hello" for item in s: if item =="l": break print(item) 运算结果: h e
4,列表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 """ 8 L.append(object) -- append object to end """ 9 pass 10 11 def count(self, value): # real signature unknown; restored from __doc__ 12 """ 查看lst中某一项出现的次数 13 L.count(value) -> integer -- return number of occurrences of value """ 14 return 0 15 16 def extend(self, iterable): # real signature unknown; restored from __doc__ 17 """将原列表与其他列表扩展成新列表 18 L.extend(iterable) -- extend list by appending elements from the iterable """ 19 pass 20 21 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 22 """返回列表中第一个匹配项的下标,找不到会报错 23 L.index(value, [start, [stop]]) -> integer -- return first index of value. 24 Raises ValueError if the value is not present. 25 """ 26 return 0 27 28 def insert(self, index, p_object): # real signature unknown; restored from __doc__ 29 """在指定位置插入项 30 L.insert(index, object) -- insert object before index """ 31 pass 32 33 def pop(self, index=None): # real signature unknown; restored from __doc__ 34 """返回指定位置的值,并将其从列表中删除。默认对末尾项操作 35 L.pop([index]) -> item -- remove and return item at index (default last). 36 Raises IndexError if list is empty or index is out of range. 37 """ 38 pass 39 40 def remove(self, value): # real signature unknown; restored from __doc__ 41 """从列表中移除第一个符合与指定值相等的项 42 L.remove(value) -- remove first occurrence of value. 43 Raises ValueError if the value is not present. 44 """ 45 pass 46 47 def reverse(self): # real signature unknown; restored from __doc__ 48 """列表反转 49 L.reverse() -- reverse *IN PLACE* """ 50 pass 51 52 def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ 53 """排序,数字、字符串按照ASCII,中文按照unicode从小到大排序。 54 L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; 55 cmp(x, y) -> -1, 0, 1 56 """ 57 pass 58 59 def __add__(self, y): # real signature unknown; restored from __doc__ 60 """ 字符串拼接 61 x.__add__(y) <==> x+y """ 62 pass 63 64 def __contains__(self, y): # real signature unknown; restored from __doc__ 65 """ 判断列表中是否包含某一项 66 x.__contains__(y) <==> y in x """ 67 pass 68 69 def __delitem__(self, y): # real signature unknown; restored from __doc__ 70 """删除列表中指定下标的项 71 x.__delitem__(y) <==> del x[y] """ 72 pass 73 74 def __delslice__(self, i, j): # real signature unknown; restored from __doc__ 75 """删除指定下标之间的内容,向下包含 76 x.__delslice__(i, j) <==> del x[i:j] 77 78 Use of negative indices is not supported. 79 """ 80 pass 81 82 def __eq__(self, y): # real signature unknown; restored from __doc__ 83 """ 判断两个列表是否相等 84 x.__eq__(y) <==> x==y """ 85 pass 86 87 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 88 """ 无条件被调用,通过实例访问属性。 89 x.__getattribute__('name') <==> x.name """ 90 pass 91 92 def __getitem__(self, y): # real signature unknown; restored from __doc__ 93 """ x.__getitem__(y) <==> x[y] """ 94 pass 95 96 def __getslice__(self, i, j): # real signature unknown; restored from __doc__ 97 """ 98 x.__getslice__(i, j) <==> x[i:j] 99 100 Use of negative indices is not supported. 101 """ 102 pass 103 104 def __ge__(self, y): # real signature unknown; restored from __doc__ 105 """ x.__ge__(y) <==> x>=y """ 106 pass 107 108 def __gt__(self, y): # real signature unknown; restored from __doc__ 109 """ x.__gt__(y) <==> x>y """ 110 pass 111 112 def __iadd__(self, y): # real signature unknown; restored from __doc__ 113 """ x.__iadd__(y) <==> x+=y """ 114 pass 115 116 def __imul__(self, y): # real signature unknown; restored from __doc__ 117 """ 118 x.__imul__(y) <==> x*=y """ 119 pass 120 121 def __init__(self, seq=()): # known special case of list.__init__ 122 """ 123 list() -> new empty list 124 list(iterable) -> new list initialized from iterable's items 125 # (copied from class doc) 126 """ 127 pass 128 129 def __iter__(self): # real signature unknown; restored from __doc__ 130 """ x.__iter__() <==> iter(x) """ 131 pass 132 133 def __len__(self): # real signature unknown; restored from __doc__ 134 """ x.__len__() <==> len(x) """ 135 pass 136 137 def __le__(self, y): # real signature unknown; restored from __doc__ 138 """ x.__le__(y) <==> x<=y """ 139 pass 140 141 def __lt__(self, y): # real signature unknown; restored from __doc__ 142 """ x.__lt__(y) <==> x<y """ 143 pass 144 145 def __mul__(self, n): # real signature unknown; restored from __doc__ 146 """ x.__mul__(n) <==> x*n """ 147 pass 148 149 @staticmethod # known case of __new__ 150 def __new__(S, *more): # real signature unknown; restored from __doc__ 151 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 152 pass 153 154 def __ne__(self, y): # real signature unknown; restored from __doc__ 155 """ x.__ne__(y) <==> x!=y """ 156 pass 157 158 def __repr__(self): # real signature unknown; restored from __doc__ 159 """ x.__repr__() <==> repr(x) """ 160 pass 161 162 def __reversed__(self): # real signature unknown; restored from __doc__ 163 """ L.__reversed__() -- return a reverse iterator over the list """ 164 pass 165 166 def __rmul__(self, n): # real signature unknown; restored from __doc__ 167 """ x.__rmul__(n) <==> n*x """ 168 pass 169 170 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 171 """ x.__setitem__(i, y) <==> x[i]=y """ 172 pass 173 174 def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ 175 """ 176 x.__setslice__(i, j, y) <==> x[i:j]=y 177 178 Use of negative indices is not supported. 179 """ 180 pass 181 182 def __sizeof__(self): # real signature unknown; restored from __doc__ 183 """ L.__sizeof__() -- size of L in memory, in bytes """ 184 pass 185 186 __hash__ = None 187 188 list 189 190 list Code
name_list = ["eirc","alex","tony"] print(name_list) 运算结果: ['eirc', 'alex', 'tony']
基本操作:
索引 name_list = ["eirc","alex","tony"] print(name_list[0]) 运算结果: eirc 切片 name_list = ["eirc","alex","tony"] print(name_list[0:2]) 运算结果: ['eirc', 'alex'] # len name_list = ["eirc","alex","tony"] print(name_list[2:len(name_list)]) 运算结果: ['tony'] # for for i in name_list: print(i) # 列表内部提供的其他功能 append 追加 示例: name_list = ["eirc","alex","tony"] name_list.append('seven') print(name_list) 运算结果: ['eirc', 'alex', 'tony', 'seven'] 示例: name_list = ["eirc","alex","tony"] name_list.append('seven') name_list.append('seven') name_list.append('seven') name_list.append('seven') print(name_list,count('seven')) 运算结果: 4 # iterable 可迭代的 name_list = ["eirc","alex","tony"] temp = [11,22,33,44] name_list.extend(temp) print(name_list) 运算结果: ['eirc', 'alex', 'tony', 11, 22, 33, 44] index 找出所在位子的索引 name_list = ["eirc","alex","tony"] temp = [11,22,33,44] name_list.extend(temp) print(name_list.index('alex')) 运算结果: 1 insert 插入 示例: name_list = ["eirc","alex","tony"] temp = [11,22,33,44] name_list.extend(temp) name_list.insert(1,'hello') print(name_list) 运算结果: ['eirc', 'hello', 'alex', 'tony', 11, 22, 33, 44] pop 移除尾部的参数并且可以赋值到一个变量上a1 示例: name_list = ["eirc","alex","tony"] temp = [11,22,33,44] name_list.extend(temp) name_list.insert(1,'hello') print(name_list) a1 = name_list.pop() print(name_list) print(a1) 运算结果: ['eirc', 'hello', 'alex', 'tony', 11, 22, 33, 44] ['eirc', 'hello', 'alex', 'tony', 11, 22, 33] 44 remove 移除一个 要想都移除只能多次执行 示例: name_list = ['eirc', 'hello','alex', 'alex', 'tony', 11, 22, 33, 44] name_list.remove('alex') print(name_list) 运算结果: ['eirc', 'hello', 'alex', 'tony', 11, 22, 33, 44] reverse 翻转 示例: name_list = ['eirc', 'hello','alex', 'alex', 'tony', 11, 22, 33, 44] name_list.reverse() print(name_list) 运算结果: [44, 33, 22, 11, 'tony', 'alex', 'alex', 'hello', 'eirc'] del 删除一个索引 name_list = ["eirc","alex","tony"] del name_list[1] print(name_list) 运算结果: ['eirc', 'tony'] #切片,范围删除 name_list = ["eirc","alex","tony"] del name_list[1:3] print(name_list) 运算结果: ["eirc"]
元祖tuple
元组: name_tuple = ('alex', 'eric') # 索引 print(name_tuple[0]) # len print(name_tuple[len(name_tuple)-1]) # 切片 print(name_tuple[0:1]) # for for i in name_tuple: print(i) # 删除 # del name_tuple[0] 不支持 # count,计算元素出现的个数 print(name_tuple.count('alex')) # index 获取指定元素的索引位置 print(name_tuple.index('alex'))
字典dict
字典: name_tuple = ('alex', 'eric') # 索引 print(name_tuple[0]) # len print(name_tuple[len(name_tuple)-1]) # 切片 print(name_tuple[0:1]) # for for i in name_tuple: print(i) # 删除 # del name_tuple[0] 不支持 # count,计算元素出现的个数 print(name_tuple.count('alex')) # index 获取指定元素的索引位置 print(name_tuple.index('alex'))
详细请参考
http://www.cnblogs.com/wupeiqi/articles/5444685.html