Python变量运算字符串等

一,作用域

操作

name = 'liuyueming'

if 1==1:
... print name
...
liuyueming

两次回车执行

修改代码

>>> if 1==1:
...    name = 'zhangsan'
... print name
File "<stdin>", line 3
print name
^
SyntaxError: invalid syntax

结论:外层变量,可以被内层变量使用

   内层变量,无法被外层变量使用

只要内存里存在,则就能使用

在看一个列子

>>> name = {'nm':'123'}
>>> for item in name:
...    print item
... print item
File "<stdin>", line 3
print item
^
SyntaxError: invalid syntax

因为在for循环内部只是打印但是并没有赋值给任何变量,所以跳出循环打印item因为没有定义所以报错

 

二,三元运算

>>> name = 'liuyueming'
>>> if 1==1:
...     name = 'sb'
...   else:
...     name = '2b'

为了简化可以使用一下方式代替以上实现的功能

name = 值1 if 条件 else 值2

改成

name = 'sb' if 1==1 else '2b'

判断用户输入如果是alex给赋值'sb'否则赋值'goodmen'

>>> input = raw_input()

alex
>>> reslut = 'sb' if input == 'alex' else 'goodmen'

 

三,进制转换

二进制 01

八进制 01234567

十进制  0123456789

十六进制0123456789ABCDEF

 

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

使用tpye()查看类型

使用dir(),help()可以查看一些可以的参数和用法

dir(list)列出使用方法 help(list)列出用法

 

数据类型的内置方法

类中的方法:

    __方法__:内置方法,可能有多种执行方式

    方法        :只有一种执行方式

比如

>>> dir(int)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

n1 = 1 

n2 = 2

n1 + n2

3

另外一种执行方法

(n1).__add__(n2)

3

n1 = -9

求绝对值有两种方式

n1.__abs__()

abs(n1)

 

创建一个数值有几种方法

i = 10

i = int(10)

指定创建的进制

i = int("10",base=2)

PS:需要用引号代表是字符串转换过来的,最常用的就是创建一个10进制的整数,另外一种方式几乎不用,连接即可

(99).__divmod__(10)

(9,9)

计算商和余数

age.__float__()

18.0

把整数转换成浮点类型

 age.__format__("10")
' 18'

在前面加10个空格组成字符串

 

age.__hash__()

如果对象object为哈希表类型,返回对象object的哈希值,在字典查找中,哈希值用于快速比较字典的键.

PS:可用于爬虫等页面过长先计算一个哈希值或者MD5值进行比较即可

 

age.__hex__()
'0x12'

转化成16进制

age.__oct__()

转化成8进制

 

字符串的内置方法

dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

 

编码和解码

>>> '无'
'\xe6\x97\xa0'
>>> str1 = '\xe6\x97\xa0'
>>> str1
'\xe6\x97\xa0'
>>> print str1

>>> str1.decode('utf8')
u'\u65e0'
>>> str1.decode('utf8').encode('gbk')
'\xce\xde'

decode编码

encode解码

 

字符串的内置方法后续

>>> name
'alex'
>>> name.endswith('x')
True

以x结尾返回True

 

>>> name = 'ale x'
>>> name.expandtabs()
'ale        x'

把tab转换成8个空格(默认)

 name.expandtabs(1) 加参数代表转换成多少个空格

 

>>> name.find('e')
2

找到相应字符的下标(第一次出现位置的下标没有找到返回-1)

 

>>> name = "i m{0},age{1}"
>>> name.format('alex',73)
'i malex,age73'

 

也可以写成以下

>>> name = "i m{ss},age{dd}"
>>> name.format(ss='alex',dd=73)
'i malex,age73'

 

0 1占位符就是按照顺序加入,如果是字符占位符就不是严格按照位置的是按照定义的名称来区分的,不按顺序来

 

name = "i m{0},age{1}"
>>> li = [2222,3333]
>>> name.format(*li)
'i m2222,age3333'

传递一个列表或者元祖,使用*

 

>>> dic = {'ss':123,'dd':456}
>>> name = " i m {ss},age{dd}"
>>> name.format(**dic)
' i m 123,age456'

如果传递的是字典加**

 

>>> name.find('n')
-1
>>> name.index('n')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found

 

find和index的区别 一个找不到返回-1一个找不到就报错

 

>>> ('da').isalnum()
True
>>> ('爱神的箭').isalnum()
False

如果是字母和数字返回True其他返回False

 

isdigit()是否是数字

islower()是否是小写的

isspace()是否是空格

istitle()是否是标题

>>> name = 'liuyueming sb'
>>> name.istitle()
False
>>> name = 'Liuyueming Sb'
>>> name.istitle()
True

首字母为大写就是标题

 

>>> name = "Hello Alex"
>>> name.ljust(30,"=")
'Hello Alex===================='
>>> name.lower()
'hello alex'
>>> name.upper()
'HELLO ALEX'
>>> name.swapcase()
'hELLO aLEX'

 

>>> import string
>>> intab = 'aeiou'
>>> outtab = '12345'
>>> trantab = string.maketrans(intab,outtab)
>>> str = "This is string example...wow!!!"
>>> print str.translate(trantab,'xm')
Th3s 3s str3ng 21pl2...w4w!!!
字母于数字对应转换

 

列表

如[11,22,33]['zhangshan','lisi','wangwu']

append() 在尾行加一个

extend(['',''])扩展,相当于列表连接另外一个列表

index()第一次出现这个值的下标,如果不存在触发一个异常

insert()在列表的指定位置插入,指定位置为下标

pop()删除指定下标的值,如果没有指定就默认是最后一个

>>> li.pop()
'alex'
>>> li
[11, 22, 44, 66, 'alex']
>>> li.pop(1)
22
remove()指定值删除第一个

reverse()列表翻转

sort()比较排序,数字按数字大小,字符按照编码

 

元祖里的元素不能修改,所以元祖的方法较少

count()统计一个元素出现的次数

index()一个元素第一次出现的下标

 

字典及常用方法

 dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

 

dic = {'k1':1234}

>>> dic.get('k1')
1234
dic.get('k2')

如果没有就不输出但是不报错

>>> print dic.get('k2')
None

>>> dic.get('k2','ok')
'ok'
如果没有就返回一个指定的字符

 

PS:字典的key不能重复,value可以重复,列表是一个有序在状态,字典是无序的,字典没有下标而是key来唯一定位

 

>>> name_dic ={'alex':18,'rain':11}
>>> name_dic
{'alex': 18, 'rain': 11}
>>> name_dic[1] = 2
>>> name_dic
{1: 2, 'alex': 18, 'rain': 11}
key可以是数组,字符串,元祖但是不能为列表 (最好不要使用元祖作为下标不规范)

datetime.datetime.now()
datetime.datetime(2017, 4, 18, 16, 58, 21, 517031)
>>> a=datetime.datetime.now()
>>> name_dic[a] = 2
>>> name_dic
{1: 2, 'alex': 18, 'rain': 11, datetime.datetime(2017, 4, 18, 16, 58, 49, 793567): 2}
日期也可以当成是字典的key(也不合规)

一般是字符串,数字,类的实例作为key

 

>>> type(name_dic)
<type 'dict'>
>>> type(name_dic) is dict

判断是否是什么数据类型

 

>>> a={1:2}
>>> a.clear()
>>> a
{}
清除字典

 

>>> a={}
>>> a.fromkeys([1,2,3],'t')
{1: 't', 2: 't', 3: 't'}
把列表中的值当成key value是t生成一个字典

 

>>> a.fromkeys([1,2,3],'t')
{1: 't', 2: 't', 3: 't'}
>>> b=a.fromkeys([1,2,3],'t')
>>> 1 in b
True
判断1是不是字典里面的key

 

>>> b
{1: 't', 2: 't', 3: 't'}
>>> b.items()
[(1, 't'), (2, 't'), (3, 't')]

字典变成列表

 

>>> b.keys()
[1, 2, 3]
打印当前所有key

 

>>> b
{1: 't', 2: 't', 3: 't'}
>>> b.pop(1)
't'
>>> b
{2: 't', 3: 't'}

删除

也可以使用del

>>> b
{2: 't', 3: 't'}
>>> del b[2]
>>> b
{3: 't'}

>>> b.fromkeys(range(100),[])
{0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [], 11: [], 12: [], 13: [], 14: [], 15: [], 16: [], 17: [], 18: [], 19: [], 20: [], 21: [], 22: [], 23: [], 24: [], 25: [], 26: [], 27: [], 28: [], 29: [], 30: [], 31: [], 32: [], 33: [], 34: [], 35: [], 36: [], 37: [], 38: [], 39: [], 40: [], 41: [], 42: [], 43: [], 44: [], 45: [], 46: [], 47: [], 48: [], 49: [], 50: [], 51: [], 52: [], 53: [], 54: [], 55: [], 56: [], 57: [], 58: [], 59: [], 60: [], 61: [], 62: [], 63: [], 64: [], 65: [], 66: [], 67: [], 68: [], 69: [], 70: [], 71: [], 72: [], 73: [], 74: [], 75: [], 76: [], 77: [], 78: [], 79: [], 80: [], 81: [], 82: [], 83: [], 84: [], 85: [], 86: [], 87: [], 88: [], 89: [], 90: [], 91: [], 92: [], 93: [], 94: [], 95: [], 96: [], 97: [], 98: [], 99: []

 c=b.fromkeys(range(100),[])

>>> c.popitem()
(0, [])
随机删除(尽量不用)

 

>>> c.setdefault(74)
[]
>>> c.setdefault(744)
>>> c
{10: [], 11: [], 12: [], 13: [], 14: [], 15: [], 16: [], 17: [], 18: [], 19: [], 20: [], 21: [], 22: [], 23: [], 24: [], 25: [], 26: [], 27: [], 28: [], 29: [], 30: [], 31: [], 32: [], 33: [], 34: [], 35: [], 36: [], 37: [], 38: [], 39: [], 40: [], 41: [], 42: [], 43: [], 44: [], 45: [], 46: [], 47: [], 48: [], 49: [], 50: [], 51: [], 52: [], 53: [], 54: [], 55: [], 56: [], 57: [], 58: [], 59: [], 60: [], 61: [], 62: [], 63: [], 64: [], 65: [], 66: [], 67: [], 68: [], 69: [], 70: [], 71: [], 72: [], 73: [], 74: [], 75: [], 76: [], 77: [], 78: [], 79: [], 80: [], 81: [], 82: [], 83: [], 84: [], 85: [], 86: [], 87: [], 88: [], 89: [], 90: [], 91: [], 92: [], 93: [], 94: [], 95: [], 96: [], 97: [], 98: [], 99: [], 744: None}

如果有则返回,没有就创建一个

>>> c.setdefault(745,['df'])
['df']
>>> c
{10: [], 11: [], 12: [], 13: [], 14: [], 15: [], 16: [], 17: [], 18: [], 19: [], 20: [], 21: [], 22: [], 23: [], 24: [], 25: [], 26: [], 27: [], 28: [], 29: [], 30: [], 31: [], 32: [], 33: [], 34: [], 35: [], 36: [], 37: [], 38: [], 39: [], 40: [], 41: [], 42: [], 43: [], 44: [], 45: [], 46: [], 47: [], 48: [], 49: [], 50: [], 51: [], 52: [], 53: [], 54: [], 55: [], 56: [], 57: [], 58: [], 59: [], 60: [], 61: [], 62: [], 63: [], 64: [], 65: [], 66: [], 67: [], 68: [], 69: [], 70: [], 71: [], 72: [], 73: [], 74: [], 75: [], 76: [], 77: [], 78: [], 79: [], 80: [], 81: [], 82: [], 83: [], 84: [], 85: [], 86: [], 87: [], 88: [], 89: [], 90: [], 91: [], 92: [], 93: [], 94: [], 95: [], 96: [], 97: [], 98: [], 99: [], 744: None, 745: ['df']}

>>> d={'a':1,'b':2,745:'alex'}
>>> c.update(d)
>>> c
{10: [], 11: [], 12: [], 13: [], 14: [], 15: [], 16: [], 17: [], 18: [], 19: [], 20: [], 21: [], 22: [], 23: [], 24: [], 25: [], 26: [], 27: [], 28: [], 29: [], 30: [], 31: [], 32: [], 33: [], 34: [], 35: [], 36: [], 37: [], 38: [], 39: [], 40: [], 41: [], 42: [], 43: [], 44: [], 45: [], 46: [], 47: [], 48: [], 49: [], 50: [], 51: [], 52: [], 53: [], 54: [], 55: [], 56: [], 57: [], 58: [], 59: [], 60: [], 61: [], 62: [], 63: [], 64: [], 65: [], 66: [], 67: [], 68: [], 69: [], 70: [], 71: [], 72: [], 73: [], 74: [], 75: [], 76: [], 77: [], 78: [], 79: [], 80: [], 81: [], 82: [], 83: [], 84: [], 85: [], 86: [], 87: [], 88: [], 89: [], 90: [], 91: [], 92: [], 93: [], 94: [], 95: [], 96: [], 97: [], 98: [], 99: [], 744: None, 745: 'alex', 'b': 2, 'a': 1}

在c里面循环查找如果有就替换 没有就添加

>>> c=c.fromkeys(range(5),[])
>>> c
{0: [], 1: [], 2: [], 3: [], 4: []}

 

>>> for i in range(5):
...     c[i] = []
...
>>>
>>> c
{0: [], 1: [], 2: [], 3: [], 4: []}
>>> c[1].append({"b":1})
>>> c
{0: [], 1: [{'b': 1}], 2: [], 3: [], 4: []}

字典默认一直指向同一个内存空间,即使数据有修改

 

copy()浅copy,不完全独立,如果源有删除数据还在,源修改数据跟着修改,要想完全独立需要使用深copy

import copy

f = copy.deepcopy(c)

 

集合

>>> a
[5, 6, 7, 8, 9]
>>> b
[7, 8, 9, 10, 11]

c=set(a)

>>> c
set([8, 9, 5, 6, 7])

set可以去重

d = set(b)

>>> c & d
set([8, 9, 7])

取交集

>>> c|d
set([5, 6, 7, 8, 9, 10, 11])

取并集

>>> c^d
set([5, 6, 10, 11])

取反的交集

>>> c -d
set([5, 6])

去c里面有d里面没有的

PS:c+d是不行的会报错

集合的方法

>>> dir(set)
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

 

e=set([8,10])

>>> e.issubset(d)
True

判断e是d的子集

 

posted @ 2017-04-14 14:32  minseo  阅读(409)  评论(0编辑  收藏  举报