zoukankan      html  css  js  c++  java
  • python-day3

    这篇主要记录学习字符串和字典的心得。

    一、字符串

    字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。

    字符串的特性:

    • 字符串中任何一个字符不可以被修改;
    • 字符串与字符串只能合并;
    • 只能获取字符串中的一个或者多个字符串;

    1、字符串的创建

    创建字符串很简单,只要为变量分配一个值即可。

    >>> name='bianbian'
    >>> name1="bianbian"
    >>> name2='''bianbian'''
    >>> name
    'bianbian'
    >>> name1
    'bianbian'
    >>> name2
    'bianbian'
    

    也可以定义空字符串, 单引号、双引号、三引号都可以定义字符串。

    注:

    • 三引号支持多行 ;
    • 三引号包含双引号和单引号,双引号包含单引号;

    字符串不支持修改,强制修改报错。

    >>> name[3]='v'
    Traceback (most recent call last):
      File "<pyshell#6>", line 1, in <module>
        name[3]='v'
    TypeError: 'str' object does not support item assignment

    2、字符串的切片

    字符串和列表,元组一样,也是可以切片.

    >>> name[2:5]
    'anb'
    >>> name[:]
    'bianbian'
    >>> name[2:-1]
    'anbia'
    >>> name[::2]
    'baba'
    >>> name[0:-2]
    'bianbi'
    

    3、字符串的常用方法

    通过dir()可以查看字符串的所有方法,下面对常用的一些方法解释操作一下。

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

    1、capitalize() 字符串的首字母大写

    >>> name.capitalize()
    'Bianbian'
    

    2、center(width,fillchar) 、ljust(width,fillchar)、rjust(width,fillchar)

    这三个方法放在一起说,比较容易记忆和理解。

    对于center()方法,如果width(字符宽度)小于等于(<=)字符串的长度,则返回原字符串,如果大于(>)字符串的,则用fillchar(填满字符)填满,处理结果等于width,字符串位于fillchar的中间

    ljust()方法,如果字符串的长度大于width(字符宽度),则返回原字符串,如果小于width,则用fillchar(填满字符)填满,处理结果等于width,fillchar位于字符串的最右边

    同理,rjust(),如果字符串的长度大于width(字符宽度),则返回原字符串,如果小于width,则用fillchar(填满字符)填满,处理结果等于width,fillchar位于字符串的最左边

    注意:ljust中的l表示left的意思,表示从右向左;rjust中的r表示right的意思,表示从左向右;

    >>> name.center(20,'1')
    '111111bianbian111111'
    >>> name.rjust(30,'2')
    '2222222222222222222222bianbian'
    >>> name.ljust(25,'_')
    'bianbian_________________'
    

     3、count(sub,start=None,end=None)

    统计某个字符或者字符串在整个字符串中的个数。

    >>> name.count('a')
    2
    >>> name.count('bianbian')
    1
    

     4、endswith(suffix,start=None.end=None),startswith(suffix,start=None.end=None)

    endswith()判断字符串是否以suffix结尾,是的话返回True,不是则返回False;

    反之,startswith()判断字符串是否以suffix开头,是的话返回True,不是则返回False;

    >>> name.endswith('b')
    False
    >>> name.endswith('an')
    True
    >>> name.startswith('b')
    True
    >>> name.startswith('aa')
    False
    

     5、find(sub,start=None,end=None),rfind(sub,start=None,end=None)

     find():全文查找sub中第一个字符所在整个字符串中的索引值,没有找到则返回-1;

    rfind():从左向右查找sub中第一个字符所在整个字符串中的索引值,没有找到则返回-1;

    sub:字符或者字符串,start:开始位,end:结束位,start和end默认为空时,则在整个字符串中查找

    >>> name.find('a',2,5)
    2
    >>> name.find('q')
    -1
    >>> name.rfind('s',0,9)
    -1
    >>> name.rfind('s',3)
    -1
    

    6、format(),format_map()

    format()做字符串拼接:

    • 关键字拼接 

      关键字拼接不受参数位置影响:

    name = "bianbian"
    age = 18
    info = '''----info:----
    name:{_name}
    age:{_age}
    '''.format(_name=name,_age=age)
    print(info)
    
    • 占位符拼接 (推荐)

    占位符拼接受参数位置影响: 

    name = "bianbian"
    age = 18
    info = '''info:+---
    name:{0}
    age:{1}
    '''.format(name,age)
    print(info)
    
    • format_map() 数据格式,以字典形式传入
    >>> name='name:{name},age:{age}'
    >>> name.format_map({'name':'bianbian','age':18})
    'name:bianbian,age:18'
    

     7、isalnum()、isalpha()、isdigit()

    isalnum():判断字符串是否由阿拉伯数字字母,字符串仅包含英文字符和(1-9)的阿拉伯数字,且中间不能有特殊字符时返回true,否则返回false;

    isalpha():判断字符串是否是纯英文字符,包含大写;

    isdigit():判断字符串是否是一个整数;

    >>> name = 'bian0508'
    >>> name.isalnum()
    True
    >>> name ='3298__hfksa'
    >>> name.isalnum()
    False
    >>> name.isalpha()
    False
    >>> name.isdigit()
    False
    

    8、isspace()、istitle()、isupper()

    isspace():判断字符串中是否有空格;

    istitle():判断字符串是否是标题(字符串中的每个单子首字母大写);

    isupper():判断字符串是否大写,注意字符串必须全部是大写才会返回True,否则返回False;

    >>> name.isdigit()
    False
    >>> name.isspace()
    False
    >>> name.istitle()
    False
    >>> name.isupper()
    False
    >>> name='ADH'
    >>> name.isupper()
    True
    

    9、lower()、upper()、swapcase() 

     lower():字符串中的大写字母转换为小写字母;

    upper():字符串中的小写字母转换为大写字母;

    swapcase():字符串中的大写换成小写,把小写换成大写;

    >>> name = 'BianBian'
    >>> name.lower()
    'bianbian'
    >>> name.upper()
    'BIANBIAN'
    >>> name.swapcase()
    'bIANbIAN'
    

     10、join()、index(sub,start=None,end=None)

    join():序列用某个字符拼接成一个字符串,注意的是,序列的元素必须是str类型;

    index():查找某个sub(字符或者子字符串)在字符串中的索引值,如果没找到会报错:ValueError: substring not found

    >>> b = ['a','b','c']
    >>> '+'.join(b)
    'a+b+c'
    >>> name.index('b')
    Traceback (most recent call last):
      File "<pyshell#57>", line 1, in <module>
        name.index('b')
    ValueError: substring not found
    >>> name.index('a')
    2
    >>> name.index('an')
    2

     11、strip()、lstrip()、rstrip() 

    strip():删除左右两边的空格(space)和回车( );

    lstrip():删掉字符串右边的空格(space)和回车( );

    rstrip():删掉字符串左边的空格(space)和回车( );

    >>> name = '   
    bianbian
         '
    >>> name.strip()
    'bianbian'
    >>> name.rstrip()
    '   
    bianbian'
    >>> name.lstrip()
    'bianbian
         '
    

    12、split()、splitlines()、replace(old,new[, max])、zfill(width)

     split():分割函数,默认是以空格分割(space)生成一个列表,如果其他字符分割,输入其他字符参数;

       splitlines():以换行符分割,这个一般在windows上开发,移到Linux上执行,或者在Linux上开发,移到Windows上执行,因为换行在windows上是" ",linux上是' '

    >>> name ='bian bian'
    >>> name.split()
    ['bian', 'bian']
    >>> name.split('a')
    ['bi', 'n bi', 'n']
    >>> name ='bian
    bian
    bian'
    >>> name.splitlines()
    ['bian', 'bian', 'bian']
    

    replace(old,new[, max]):old:将被替换的子字符串; new:新字符串,用于替换old子字符串;max:可选字符串, 替换不超过 max 次,如果没有max,默认字符串zhong的全部替换;

    zfill(width):如果字符的长度如果比width小,则在字符串钱用0填充,如果>=width,则返回原字符串;

    >>> name ='bian
    bian
    bian'
    >>> name.replace('an','pp',2)
    'bipp
    bipp
    bian'
    >>> name.replace('an','pp')
    'bipp
    bipp
    bipp'
    >>> name.replace('an','pp',1)
    'bipp
    bian
    bian'
    >>> name.zfill(30)
    '0000000000000000bian
    bian
    bian'
    >>> name.zfill(3)
    'bian
    bian
    bian'
    

    二、字典

    字典是另一种可变容器模型,且可存储任意类型对象。字典是key:value的数据类型,通过key去访问value 。

     字典特性

    • 字典是无序的
    • 字典是通过key去访问value
    • 字典元素不可重复

    1、字典定义

    字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:

    键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。

    d = {key1 : value1, key2 : value2 }

    >>> d ={'a':4,'b':5,'c':6}
    >>> d['b']
    5
    >>> d
    {'a': 4, 'b': 5, 'c': 6}

    2、访问字典

    把相应的键放入熟悉的方括弧,如下实例:

    >>> d={'name':'bianbian','age':18}      
    >>> d       
    {'name': 'bianbian', 'age': 18}
    >>> d['name']       
    'bianbian'
    

    3、字典的基本用法

    1、增加

    >>> d={'name':'bianbian,'age':18}
    >>> d['score']=100
           
    >>> d
           
    {'name': 'bianbian', 'age': 18, 'score': 100}
    

    2、修改

    >>> d
           
    {'name': 'bianbian', 'age': 18, 'score': 100}
    >>> d['name']='pengpeng'
           
    >>> d
           
    {'name': 'pengpeng', 'age': 18, 'score': 100}
    

    3、删除(del、pop、popitem) 

    1、del

    >>> d
           
    {'name': 'pengpeng', 'age': 18, 'score': 100}
    >>> del d['score']
           
    >>> d
           
    {'name': 'pengpeng', 'age': 18}

    >>> del d
    # 如果是del d的话,则是删除d这个字典
    >>> d

    Traceback (most recent call last):
    File "<pyshell#108>", line 1, in <module>
    d
    NameError: name 'd' is not defined

    注:如果是del d的话,则是删除d这个字典

    2、pop

    >>> d
           
    {'name': 'pengpeng', 'age': 18}
    >>> d.pop('name')
           
    'pengpeng'
    >>> d
           
    {'age': 18}

    3、popitem

    随机删除字典中的一个元素
    >>> d={'name': 'bianbian', 'age': 18, 'score': 100}
    
    >>> d.popitem()
           
    ('score', 100)
    >>> d
           
    {'name': 'bianbian', 'age': 18}
    

    4、查找

    1、key值在字典中存在

    >>> d={'name':'bianbian','age':18}
           
    >>> 'bianbian' in d
           
    False
    >>> 'name' in d
           
    True
    

    key in dict 这种查找方式,可以在Python 3 也可以在Python 2.7中使用;

    dict.has_key(key)在python 3 中已经废弃

    >>> stu_info.has_key("name") 
    True

    2、get(key)

    >>> d={'name':'bianbian','age':18}
           
    >>> d.get('name')
           
    'bianbian'
    >>> d.get('bianbian')
           
    >>> 
    

    3、通过key获取value  

    通过key获取value,存在key,则返回value,如果不存在,则报错:keyerror

    >>> d={'name':'bianbian','age':18}
    
    >>> d['name']
           
    'bianbian'
    >>> d['bianbian']
           
    Traceback (most recent call last):
      File "<pyshell#123>", line 1, in <module>
        d['bianbian']
    KeyError: 'bianbian'  

    查找方法小结:

    • get(key)不存在key值,则返回None;通过key直接访问会报错,所以建议推荐用get(key)这个方法获取value; 
    • key in dict 这种查找方式,可以在Python 3 也可以在Python 2.7中使用;
    • dict.has_key(key)在python 3 中已经废弃

    5、多级字典嵌套及操作

    >>> d={'bianfengjie':{'name':'bianbian','age':18,'score':100},'shenjinpeng':{'name':'pengpeng','age':19,'score':101}}
           
    >>> d
           
    {'bianfengjie': {'name': 'bianbian', 'age': 18, 'score': 100}, 'shenjinpeng': {'name': 'pengpeng', 'age': 19, 'score': 101}}
    >>> 
    

    6、values()、keys()、setdefault(k,v)

    value():返回字典中所有value,生成一个列表;

    key():返回字典中所有key,生成一个列表;

    setdefault():表示取字典中的key,如果取不到,则设置新值,相反如果取到,则返回原有默认值 

    >>> d={'name':'bianbian','age':18}      
    >>> d.values()      
    dict_values(['bianbian', 18])
    >>> d.keys()
    dict_keys(['name', 'age'])
    >>> d.setdefault('score',25)      
    25
    >>> d    
    {'name': 'bianbian', 'age': 18, 'score': 25}
    >>> d.setdefault('score',100)      
    25
    >>> d       
    {'name': 'bianbian', 'age': 18, 'score': 25}
    

    7、update(dict)、items()、fromkeys(list,默认值)、clear()

    update():把两个字典合并成一个新的字典,中间有重复的key,更新替换成新值,没有重复就直接创建;

    items():把字典转换成列表;

    fromkeys(list,默认值):初始化一个字典;

    clear():清空字典

    >>> d
           
    {'name': 'bianbian', 'age': 18, 'score': 25}
    >>> d1={'name':'pengpeng','phone':110}
           
    >>> d.update(d1)
           
    >>> d
           
    {'name': 'pengpeng', 'age': 18, 'score': 25, 'phone': 110}
           
    >>> d.items()
           
    dict_items([('name', 'pengpeng'), ('age', 18), ('score', 25), ('phone', 110)])
    >>> d.fromkeys(['age','score'],100)
           
    {'age': 100, 'score': 100}
    >>> d
           
    {'name': 'pengpeng', 'age': 18, 'score': 25, 'phone': 110}
    >>> d.clear()
           
    >>> d
           
    {}
    

     4、循环字典

    d = {'name': 'pengpeng', 'age': 18, 'score': 25, 'phone': 110}
    #方法1
    for key in d:
    	print(key, d[key])
    #方法2
    for (k,v) in d.items():
    	print(k,v)  

     结果是一样的:

    ('phone', 110)
    ('age', 18)
    ('score', 25)
    ('name', 'pengpeng')  

    小结:

    • 方法1的效率比方法2的效率高,方法1是直接通过key取value;方法2是先把字典转换成一个列表,再去取值;
    • 当数据量比较大的时候,推荐使用第一种方法
  • 相关阅读:
    Delimiter must not be alphanumeric or backslash php
    mysql replace用法
    MySQL transaction
    最大子数组问题
    LUP分解法求解线性方程组
    PHP和MySQL Web开发从新手到高手,第9天-总结
    DRBD+Heartbeat+mysql 高可用性负载均衡
    优秀博客网址
    rsync+inotify 实时同步数据
    Bugfree 搭建
  • 原文地址:https://www.cnblogs.com/bianfengjie/p/9381721.html
Copyright © 2011-2022 走看看