Python学习(二)

  • Python基本数据类型

  1. Python基本数据类型:
    1、字符串
    2、数字
    3、布尔值:bool,只有True和False两个值,Python中首字母都大写,Java中写法为true和false
    4、列表
    5、元组
    6、字典
  • 字符串详解

  1. + :用作字符串连接
    a = 'hello ';
    b = 'world';
    c = a + b;  //结果为hello world
  2. * :让字符串重复

    a = 'alex';
    n = a * 10;  //n的值为10个alex字符串的拼接
  3. 字符串的API:
    1、 capitalize()将字符串的第一个字母变成大写,其他字母变小写。
    >>>s = 'a, B'
    >>> s.capitalize()
    'A, b'
    >>> s = ' a, B' # a 前面有空格
    >>> s.capitalize()
    ' a, b'
    >>> s = 'a, BCD'
    >>> s.capitalize()
    'A, bcd'

    2、casefold()和lower()转换字符串中所有大写字符为小写。区别是:lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold() 方法。

    S1 = "Runoob EXAMPLE....WOW!!!" #英文
    S2 = "ß"  #德语
     
    print( S1.lower() )
    print( S1.casefold() )
    print( S2.lower() )
    print( S2.casefold() ) #德语的"ß"正确的小写是"ss"
    
    以上实例输出结果如下:
    runoob example....wow!!!
    runoob example....wow!!!
    ß
    ss

     3、 center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格,可指定字符填充。

    center()方法语法:
    
    str.center(width[, fillchar])
    参数
    width -- 字符串的总宽度。
    fillchar -- 填充字符。
    返回值
    该方法返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。
    例如:
    >>>str = 'runoob'
    >>> str.center(20, '*')
    '*******runoob*******'
    >>> str.center(20)
    ' runoob '

    4、encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

    encode()方法语法:
    
    str.encode(encoding='UTF-8',errors='strict')
    参数
    encoding -- 要使用的编码,如"UTF-8"。
    errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
    返回值
    该方法返回编码后的字符串。
    
    str = "this is string example....wow!!!";
    
    print "Encoded String: " + str.encode('base64','strict')
    以上实例输出结果如下:
    
    Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=

    5、decode() 方法以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。

    str.decode(encoding='UTF-8',errors='strict')
    参数
    encoding -- 要使用的编码,如"UTF-8"。
    
    errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
    
    返回值
    该方法返回解码后的字符串。
    
    str = "this is string example....wow!!!";
    str = str.encode('base64','strict');
    print "Encoded String: " + str;
    print "Decoded String: " + str.decode('base64','strict')
    以上实例输出结果如下:
    
    Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
    
    Decoded String: this is string example....wow!!!

    6、endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

    str.endswith(suffix[, start[, end]])
    参数
    suffix -- 该参数可以是一个字符串或者是一个元素。
    start -- 字符串中的开始位置。
    end -- 字符中结束位置。
    返回值
    如果字符串含有指定的后缀返回True,否则返回False。
    
    
    str = "this is string example....wow!!!";
    suffix = "wow!!!";
    print str.endswith(suffix);
    print str.endswith(suffix,20);
    suffix = "is";
    print str.endswith(suffix, 2, 4);
    print str.endswith(suffix, 2, 6);
    以上实例输出结果如下:
    
    True
    True
    True
    False

    7、startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

    startswith()方法语法:
    
    str.startswith(str, beg=0,end=len(string));
    参数
    str -- 检测的字符串。
    strbeg -- 可选参数用于设置字符串检测的起始位置。
    strend -- 可选参数用于设置字符串检测的结束位置。
    返回值
    如果检测到字符串则返回True,否则返回False。
    
    
    str = "this is string example....wow!!!";
    print str.startswith( 'this' );
    print str.startswith( 'is', 2, 4 );
    print str.startswith( 'this', 2, 4 );
    以上实例输出结果如下:
    
    True
    True
    False

    8、find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

    find()方法语法:
    
    str.find(str, beg=0, end=len(string))
    参数
    str -- 指定检索的字符串
    beg -- 开始索引,默认为0。
    end -- 结束索引,默认为字符串的长度。
    
    
    str1 = "this is string example....wow!!!";
    str2 = "exam";
    print str1.find(str2);
    print str1.find(str2, 10);
    print str1.find(str2, 40);
    以上实例输出结果如下:
    
    15
    15
    -1

    9、Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。

    >>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
    'hello world'
    >>> "{0} {1}".format("hello", "world") # 设置指定位置
    'hello world'
    >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
    'world hello world'
    
    print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
    # 通过字典设置参数
    site = {"name": "菜鸟教程", "url": "www.runoob.com"}
    print("网站名:{name}, 地址 {url}".format(**site))
    # 通过列表索引设置参数
    my_list = ['菜鸟教程', 'www.runoob.com']
    print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
    输出结果为:
    
    网站名:菜鸟教程, 地址 www.runoob.com
    网站名:菜鸟教程, 地址 www.runoob.com
    网站名:菜鸟教程, 地址 www.runoob.com

    10、format_map()    作用与format相同,只不过所需参数为字典
    11、index()    作用与find相同,但是如果未发现子字符串就报错
    12、isalnum()   是否是数字字母字符串(可以是数字字符串、字母字符串、数字字母字符串) 
    13、 expandtabs() 方法把字符串中的 tab 符号(' ')转为空格,tab 符号(' ')默认的空格数是 8。

    str.expandtabs(tabsize=8)
    参数
    tabsize -- 指定转换字符串中的 tab 符号('	')转为空格的字符数。
    返回值
    该方法返回字符串中的 tab 符号('	')转为空格后生成的新字符串。
    
    
    str = "this is	string example....wow!!!";
    
    
    print "Original string: " + str;
    print "Defualt exapanded tab: " +  str.expandtabs();
    print "Double exapanded tab: " +  str.expandtabs(16);
    以上实例输出结果如下:
    
    Original string: this is        string example....wow!!!
    Defualt exapanded tab: this is string example....wow!!!
    Double exapanded tab: this is         string example....wow!!!

    14、isalpha()   是否是字母
    15、isdecimal()   是否是数字,只能判断十进制数
    16、isdigit()   是否是数字,功能更加强大,可以判断特殊字符②等
    17、isidentifier()    是否是标识符
    18、islower()   是否是小写字母
    19、isnumeric()   是否是数字,支持中文如  二返回值是True
    20、isprintable()   是否存在不可见或不可显示的内容
    21、istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
    22、 title() 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写。

    title()方法语法:
    
    str.title();
    参数
    NA。
    返回值
    返回"标题化"的字符串,就是说所有单词都是以大写开始。
    
    
    str = "this is string example....wow!!!";
    print str.title();
    以上实例输出结果如下:
    
    This Is String Example....Wow!!!

    23、 join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

    str.join(sequence)
    参数
    sequence -- 要连接的元素序列。
    返回值
    返回通过指定字符连接序列中元素后生成的新字符串。
    
    
    str = "-";
    seq = ("a", "b", "c"); # 字符串序列
    print str.join( seq );
    以上实例输出结果如下:
    
    a-b-c

    24、ljust()、rjust()   和center用法类似
    25、 zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。

    str.zfill(width)
    参数
    width -- 指定字符串的长度。原字符串右对齐,前面填充0。
    返回值
    返回指定长度的字符串。
    
    
    str = "this is string example....wow!!!";
    
    print str.zfill(40);
    print str.zfill(50);
    以上实例输出结果如下:
    
    00000000this is string example....wow!!!
    000000000000000000this is string example....wow!!!

    26、isupper()   是否是大写字母
    27、upper()   将字符串全变为大写字母
    28、 lstrip() 方法用于截掉字符串左边的空格或指定字符。

    strip()方法语法:
    
    str.lstrip([chars])
    参数
    chars --指定截取的字符。
    返回值
    返回截掉字符串左边的空格或指定字符后生成的新字符串。
    
    str = "     this is string example....wow!!!     ";
    print str.lstrip();
    str = "88888888this is string example....wow!!!8888888";
    print str.lstrip('8');
    以上实例输出结果如下:
    
    this is string example....wow!!!
    this is string example....wow!!!8888888

    29、rstrip() 删除 string 字符串末尾的指定字符(默认为空格)

    rstrip()方法语法:
    
    str.rstrip([chars])
    参数
    chars -- 指定删除的字符(默认为空格)
    返回值
    返回删除 string 字符串末尾的指定字符后生成的新字符串。
    
    
    str = "     this is string example....wow!!!     ";
    print str.rstrip();
    str = "88888888this is string example....wow!!!8888888";
    print str.rstrip('8');
    以上实例输出结果如下:
    
         this is string example....wow!!!
    88888888this is string example....wow!!!

    30、

    strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

    注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

    strip()方法语法:
    
    str.strip([chars]);
    参数
    chars -- 移除字符串头尾指定的字符序列。
    返回值
    返回移除字符串头尾指定的字符生成的新字符串。
    
    
    str = "00000003210Runoob01230000000";
    print str.strip( '0' ); # 去除首尾字符 0
    str2 = " Runoob "; # 去除首尾空格
    print str2.strip();
    以上实例输出结果如下:
    
    3210Runoob0123
    Runoob

    31、

    maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

    注:两个字符串的长度必须相同,为一一对应的关系。

    maketrans()方法语法:
    
    str.maketrans(intab, outtab)
    参数
    intab -- 字符串中要替代的字符组成的字符串。
    outtab -- 相应的映射字符的字符串。
    返回值
    返回字符串转换后生成的新字符串。
    
    
    from string import maketrans   # 必须调用 maketrans 函数。
    
    intab = "aeiou"
    outtab = "12345"
    trantab = maketrans(intab, outtab)
    
    str = "this is string example....wow!!!";
    print str.translate(trantab);

    以上实例输出结果如下:

    th3s 3s str3ng 2x1mpl2....w4w!!!

    32、translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。

    translate()方法语法:
    
    str.translate(table[, deletechars]);
    参数
    table -- 翻译表,翻译表是通过maketrans方法转换而来。
    deletechars -- 字符串中要过滤的字符列表。
    返回值
    返回翻译后的字符串。
    
    from string import maketrans # Required to call maketrans function.
    intab = "aeiou"
    outtab = "12345"
    trantab = maketrans(intab, outtab)
    str = "this is string example....wow!!!";
    print str.translate(trantab, 'xm');
    以上实例输出结果:
    
    th3s 3s str3ng 21pl2....w4w!!!

    33、

    partition() 方法用来根据指定的分隔符将字符串进行分割。

    如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

    partition() 方法是在2.5版中新增的。

    str = "www.runoob.com"
    print str.partition(".")
    输出结果为:
    
    ('www', '.', 'runoob.com')

    34、

    rpartition() 方法类似于 partition() 方法,只是该方法是从目标字符串的末尾也就是右边开始搜索分割符。。

    如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
    35、split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串

    split() 方法语法:
    
    str.split(str="", num=string.count(str)).
    参数
    str -- 分隔符,默认为所有的空字符,包括空格、换行(
    )、制表符(	)等。
    num -- 分割次数。默认为 -1, 即分隔所有。
    返回值
    返回分割后的字符串列表。
    
    txt = "Google#Runoob#Taobao#Facebook"
    # 第二个参数为 1,返回两个参数列表
    x = txt.split("#", 1)
    print x
    以上实例输出结果如下:
    
    ['Google', 'Runoob#Taobao#Facebook']

    36、rsplit() 
    37、splitlines() 按照行(' ', ' ', ')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

    str1 = 'ab c
    
    de fg
    kl
    '
    print str1.splitlines();
    str2 = 'ab c
    
    de fg
    kl
    '
    print str2.splitlines(True)
    以上实例输出结果如下:
    
    ['ab c', '', 'de fg', 'kl']
    ['ab c
    ', '
    ', 'de fg
    ', 'kl
    ']

    38、 swapcase() 方法用于对字符串的大小写字母进行转换。

    str = "this is string example....wow!!!";
    print str.swapcase();
    str = "THIS IS STRING EXAMPLE....WOW!!!";
    print str.swapcase();
    以上实例输出结果如下:
    
    THIS IS STRING EXAMPLE....WOW!!!
    this is string example....wow!!!

    39、字符串一创建就不可修改,和Java的概念是一样的
    40、len(str)  获取字符串长度

  • 列表List详解

  1. 用[]括起来
  2. 用,分割每个元素
  3. 列表中的元素可以是任意类型,所有值都可以修改
  4. 可以通过下标取列表值:如
    list = [1,2,3,4]
    
    list[0]的值即是1
  5. 可以用for、while循环遍历
    list = [1,2,3,4];
    
    for  li  in list:
        print(li);
  6. 内容可以修改,底层实现是链表,可以通过切片取值
    list = [1,2,3,4]
    
    list[0:2]的值即是 1 2 3
  7. 删除
    del  list[0]
  8. 字符串转列表
    list('abc');  //  ['a','b','c']
  9. 列表转字符串,如果字符串既有数字又有字母,就使用循环处理,如果只有字母:" ".join(li)即可
  10. none表示空值
  11. API:
    1、append() 把元素加到列表最后
    2、clear()  清空列表
    3、copy() 复制,浅拷贝
    4、count() 计算元素出现的次数
    5、index()  寻找元素的索引
    6、insert() 插入值
    7、pop()  弹出某个值,默认最后一个,从列表删除并返回
    8、remove()  删除某个值
    9、reverse() 反转列表
    10、sort()  排序
原文地址:https://www.cnblogs.com/PCBullprogrammer/p/10134119.html