初识python(一)

 1、字符串操作


def demo_string():
    stra = 'hello world"'
    print stra.capitalize()    #首字母大写
    print stra.replace('world', 'nowcoder')
    strb = '   \n\rhello nowcoder \r\n  '
    print 0, strb
    print 1, strb.lstrip()
    print 2, strb.rstrip(), "xx"
    strc = 'hello w'
    print 3, strc.startswith('hel')
    print 4, strc.endswith('x')
    print 5, stra + strb + strc
    print 6, len(stra), len(strb), len(strc)
    print 7, 'x'.join(['a', 'b', 'c'])  # StringBuilder
    print 8, strc.split(' ')
    print 9, strc.find('llo')

 Hello world"
hello nowcoder"
0    
hello nowcoder 
  
1 hello nowcoder 
  
2    
hello nowcoder xx
3 True
4 False
5 hello world"   
hello nowcoder 
  hello w
6 12 24 7
7 axbxc
8 ['hello', 'w']
9 2

2、常见运算符 

def demo_operation():
    print 1, 1 + 2, 5 / 2, 5 * 2, 5 - 2
    print 1, 1 + 2, 5 / 2.0, 5 * 2, 5 - 2
    print 2, True, not True, not False
    print 3, 1 << 2, 88 >> 2  # 0x11111
    print 4, 1 < 2, 5 < 3
    print 5, 5 | 3, 5 & 3, 5 ^ 3  # 0x101 0x011
    x = 3
    y = 5.0
    print x, y, type(x), type(y)

1 3 2 10 3
1 3 2.5 10 3
2 True False True
3 4 22
4 True False
5 7 1 6
3 5.0 <type 'int'> <type 'float'>

3、常用函数

def demo_buildinfunction():
    print 1, max(2, 1), min(5, 3)
    print 2, len('xxx'), len([1, 2, 3])
    print 3, abs(-2), abs(7)
    print 4, range(1, 10, 2)        #start stop step
    # print 5, '\n'.join(dir(list))
    x = 2
    print x*2+4
    print 6, eval('x*2+4')
    print 7, chr(66), ord('a')
    print 8, divmod(11, 3)  # 余商

1 2 3
2 3 3
3 2 7
4 [1, 3, 5, 7, 9]
8
6 8
7 B 97
8 (3, 2) 

4、判断、循环 

def demo_controlflow():
    score = 65
    if score > 99:
        print 1, 'A'
    elif score > 60:
        print 2, 'B'
    else:
        print 3, 'C'
    while score < 100:
        print score
        score += 10
        if score > 80:
            break

    # for (int i = 0; i < 10; ++i)
    for i in range(0, 10):
        if i == 0:
            pass
        if i == 3:
            continue
        if i < 5:
            print i * i
        if i == 7:
            break

            # print i

2 B
65
75
0
1
4
16 

5、list 操作

def demo_list():
    lista = [1, 2, 3]  # vector<int> ArrayList<Integer>
    print 1, lista
    # print dir(list)
    listb = ['a', 1, 1.1]
    print 2, listb
    lista.extend(listb)
    print 3, lista
    print 4, len(lista)
    print 5, 'a' in lista, 'b' in lista
    lista = lista + listb
    print lista
    listb.insert(0, 'wwwwwww')
    print listb
    listb.pop(1)
    print listb
    listb.sort()
    print listb
    print listb[1], listb[2]
    print listb * 2
    print [0] * 10  # memset
    listb.append('xxx')
    print listb
    listb.reverse()
    print listb
    t = (1, 1, 3)  # pair<int, xxx>  #不可变的list
    print t
    print t.count(1), len(t) #t.count(num) 元组里面有多少个num

1 [1, 2, 3]
2 ['a', 1, 1.1]
3 [1, 2, 3, 'a', 1, 1.1]
4 6
5 True False
[1, 2, 3, 'a', 1, 1.1, 'a', 1, 1.1]
['wwwwwww', 'a', 1, 1.1]
['wwwwwww', 1, 1.1]
[1, 1.1, 'wwwwwww']
1.1 wwwwwww
[1, 1.1, 'wwwwwww', 1, 1.1, 'wwwwwww']
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 1.1, 'wwwwwww', 'xxx']
['xxx', 'wwwwwww', 1.1, 1]
(1, 1, 3)
2 3 

6、map操作 

def add(a, b):
    return a + b


def sub(a, b):
    return a - b


def demo_dict():
    dicta = {4: 16, 1: 1, 2: 4, 3: 9, 'a': 'b'}
    print 1, dicta
    print 2, dicta.keys(), dicta.values()
    for key, value in dicta.items():
        print 3, key, value
    for key in dicta.keys():
        print 4, key
    print 5, dicta.has_key(1), dicta.has_key(11)

    dictb = {'+': add, '-': sub}
    print 6, dictb['+'](1, 2)
    print 7, dictb.get('-')(6, 2)

    print 8, dictb
    del dictb['+']
    print 9, dictb

    dictb.pop('-')
    print 10, dictb

    dictb['x'] = 'y'
    print dictb
    # Map.put(key, value)

1 {'a': 'b', 1: 1, 2: 4, 3: 9, 4: 16}
2 ['a', 1, 2, 3, 4] ['b', 1, 4, 9, 16]
3 a b
3 1 1
3 2 4
3 3 9
3 4 16
4 a
4 1
4 2
4 3
4 4
5 True False
6 3
7 4
8 {'+': <function add at 0x03987070>, '-': <function sub at 0x039870B0>}
9 {'-': <function sub at 0x039870B0>}
10 {}
{'x': 'y'}

7、set操作 

def demo_set():
    lista = (1, 2, 3)
    listz = [1, 2, 3, 4]
    setz = set(listz)
    print 0, setz
    seta = set(lista)
    print 1, seta
    setb = set((2, 3, 4))
    print 2, seta.intersection(setb)
    print 3, seta & setb
    print 4, seta | setb, seta.union(setb)
    print 5, seta - setb, setb - seta
    seta.add('xxx')
    print 6, seta
    print 7, len(seta)
    print seta.isdisjoint(set(('a', 'b')))
    print 8, 1 in seta

 0 set([1, 2, 3, 4])
1 set([1, 2, 3])
2 set([2, 3])
3 set([2, 3])
4 set([1, 2, 3, 4]) set([1, 2, 3, 4])
5 set([1]) set([4])
6 set([1, 2, 3, 'xxx'])
7 4
True
8 True

8、类与方法 

class User:
    type = 'USER'

    def __init__(self, name, uid):   #构造方法, self可以理解为this指针
        self.name = name
        self.uid = uid

    def __repr__(self):
        return 'im ' + self.name + ' ' + str(self.uid)
        # toString()


class Guest(User):
    def __repr__(self):
        return 'im guest ' + self.name + ' ' + str(self.uid)


class Admin(User):
    type = 'ADMIN'

    def __init__(self, name, uid, group):
        User.__init__(self, name, uid)
        self.group = group

    '''
    def __repr__(self):
        return 'im admin ' + self.name + ' ' + str(self.uid) + ' ' + self.group
    '''


def create_user(type):
    if type == 'USER':
        return User('u1', 1)
    elif type == 'ADMIN':
        return Admin('a1', 2, 'g1')
    else:
        return Guest('g1', 3)


def demo_object():
    user1 = User('jim', 1)
    print user1
    guest1 = Guest('lily', 2)
    print guest1
    admin1 = Admin('xiangyu', 3, 'nowcoder')
    print admin1
    print create_user('ADMIN')

 im jim 1
im guest lily 2
im xiangyu 3
im a1 2

9、异常 

def demo_exception():
    try:
        print 2 / 1
        # print 2/0
        raise Exception('Raise Error', 'XXXX')
    except Exception as e:
        print 'error', e
    finally:
        print 'clean up'

 error ('Raise Error', 'XXXX')
clean up

10、随机数 

def demo_random():
    # random.seed(1)
    # x = prex * 100007 % xxxx
    # prex = x

    for i in range(0, 5):
        print 1, random.randint(0, 100)
    print 2, int(random.random() * 100)
    print 3, random.choice(range(0, 100, 5))
    print 4, random.sample(range(0, 100, 10), 5)

    lista = [1, 2, 3, 4, 5]
    random.shuffle(lista)
    print lista

 1 20
1 37
1 85
1 21
1 70
2 12
3 5
4 [10, 80, 20, 0, 70]
[3, 1, 2, 5, 4]

11、正则表达式 

def demo_regex():
    str = 'abc123def12gh15'
    p1 = re.compile('[\d]+')
    p2 = re.compile('\d')
    print 1, p1.findall(str)
    print 2, p2.findall(str)

    str = 'axxx@163.com,bcc@google.com,c@qq.com,d@qq.com,e@163.com'
    p3 = re.compile('[\w]+@[163|qq]+\.com')
    print 3, p3.findall(str)

    str = '<html><h>title</h><body>content</body></html>'
    p4 = re.compile('<h>[^<]+</h>')
    print 4, p4.findall(str)
    p4 = re.compile('<h>[^<]+</h><body>[^<]+</body>')
    print 5, p4.findall(str)

    str = 'xx2016-08-20zzz,xx2016-8-20zzz'
    p5 = re.compile('\d{4}-\d{2}-\d{2}')
    print p5.findall(str)

 1 ['123', '12', '15']
2 ['1', '2', '3', '1', '2', '1', '5']
3 ['axxx@163.com', 'c@qq.com', 'd@qq.com', 'e@163.com']
4 ['<h>title</h>']
5 ['<h>title</h><body>content</body>']
['2016-08-20']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值