美文网首页
python数据结构--字符串

python数据结构--字符串

作者: 向上的路 | 来源:发表于2019-03-28 21:10 被阅读0次

    字符串
    1.定义:
    字符串是一个有序的,不可修改的,以引号(单引/双引号)包围的序列
    单引号: ' '
    双引号: “” “”
    三单引号:' ' ‘(多用于代码注释)
    三双引号: “ “ “(多用于代码注释)
    单引号和双引号的区别?
    都是为字符串的标准格式,只是为了区分英语中的一些语义

    >>> print("I ' am 18")
    I ' am 18
    >>> print('I "am 18')
    I "am 18
    >>>
    >>> print ('''
    ... 1
    ... 2
    ... 3
    ... ''')
    
    1
    2
    3
    
    >>> print("""
    ... 1
    ... 2
    ... 3
    ... """)
    
    1
    2
    3
    
    1. 字符串拼接
    >>> a = "jrljs"
    >>> b = " is"
    >>> c = " nice"
    >>> d = a + b + c
    >>> d
    'jrljs is nice'
    

    3.特殊字符
    特殊字符就是在字符串当中起到特殊含义的字符
    ”\“ 转义符,将字符串当中的具有特殊含义的字符的特殊含义取消掉后继续执行;
    "\n" 换行;
    ”\t“ 水平制表符,等同于tab键
    ”\“ 反斜杠符

    占位符
    在字符串当中以指定的格式符号进行占位,然后将指定的数据传入字符串
    %s 字符串占位符
    %d 数字占位符
    %f 浮点占位符
    %.2f 控制浮点型数字占位符

    >>> print("My name is %s"%("jrljs"))
    My name is jrljs
    >>> print("My name is %s"%('jrljs'))
    My name is jrljs
    >>> print('My name is %s'%('jrljs'))
    My name is jrljs
    >>>
    >>> print("I am %d years old"%(18))
    I am 18 years old
    >>>
    >>> print("My height is %f m"%(1.70))
    My height is 1.700000 m
    >>>
    >>> print("My height is %.2f m"%(1.70))
    My height is 1.70 m
    

    4.字符串的索引
    字符串中的每一个个体都称作字符也是该字符串的一个元素,每一个元素都对应一个索引值(下标),可以使用len()方法查看一个序列的长度
    比如字符串'jrljs',可以按照下图理解其下标概念,索引号从0开始

    j r l j s
    0 1 2 3 4

    字符串截取:字符串[start:end]
    截取原则:包头不包尾且截取方向是从左到右

    >>> name = "jrljs"
    >>> print(name[1:4])
    rlj
    

    步长截取:字符串[start:end:step] 按照step步长进行隔取;
    截取原则:包头不包尾
    默认步长:字符串[start:end:step] 这三个参数都有默认值,start,默认值为0;end,默认值字符串结尾元素;step,默认值为1
    步长:默认值为1,那么它的取值范围应该是1-1=0,即全部都取出来;
    步长为2,即2-1=1,即隔一个元素取一个;
    依次类推...

    若step>0,表示从左向右进行切片,此时start必须小于end才有结果。
    若step<0,还是表示从左到右,只不过要反过来切片,此时start必须大于end才有结果。可以分两步理解,第一步先反取,即[::-1]; 第二步按照从左到右,根据步长依次取值
    string = "hello world"

    >>> print(string[0:7])
    hello w
    >>> print(string[:7])
    hello w
    >>>
    >>> print(string[2:])
    llo world
    >>> print(string[:])
    hello world
    >>> print(string[::])
    hello world
    >>> print(string[::1])
    hello world
    >>> print(string[::2])
    hlowrd
    >>>
    >>> print(string[::1])
    hello world
    >>> print(string[::-1])
    dlrow olleh
    >>> print(string[9:1:-1])
    lrow oll
    >>> print(string[9:1:-2])
    lo l
    >>> print(string[1:9:-2])
    
    >>>
    
    1. 字符串查找
    参数 描述
    count 计数功能,返回自定义字符在字符串中的总个数
    find 查找,返回从左第一个指定字符的索引,找不到返回-1
    rfind 查找,返回从右第一个指定字符的索引,找不到返回-1
    index 查找,返回从左第一个指定字符的索引,找不到报错
    rindex 查找,返回从右第一个指定字符的索引,找不到报错
    >>> print(string)
    hello world
    >>> print(string.count("l"))
    3
    >>> print(string.find("l"))
    2
    >>> print(string.rfind("l"))
    9
    >>> print(string.find("L"))
    -1
    >>> print(string.rfind("L"))
    -1
    >>> print(string)
    hello world
    >>> print(string.index("o"))
    4
    >>> print(string.rindex("o"))
    7
    >>> print(string.index("O"))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found
    >>> print(string.rindex("O"))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found
    

    6.字符串分割与替换

    参数 描述
    partition 把mystr以str进行分割,分割成三部分,str前,str自身和str后
    rpartition 类似于 partition()函数,不过是从右边开始.
    splitlines 按照行分隔,返回一个包含各行作为元素的列表,按照换行符分割
    split 判断字符串的分隔符切片
    replace 从左到右替换指定的元素,可以指定替换的个数,默认全部替换
    >>> print(string)
    hello world
    >>> print(string.partition("o"))
    ('hell', 'o', ' world')
    >>> print(string.rpartition("o"))
    ('hello w', 'o', 'rld')
    >>>
    >>>
    >>> print(string)
    hello world
    >>> print(string.splitlines())
    ['hello world']
    >>> print(string.split())
    ['hello', 'world']
    >>> string2 = "hello\n world\n python\n"
    >>> print(string2)
    hello
     world
     python
    
    >>> print(string2.splitlines())
    ['hello', ' world', ' python']
    >>> print(string2.split())
    ['hello', 'world', 'python']
    >>>
    >>>
    >>> print(string)
    hello world
    >>> print(string.replace('o','O'))
    hellO wOrld
    >>> print(string.replace('o','O',1))
    hellO world
    

    7.字符串修饰

    参数 描述
    center 让字符串在指定的长度居中,如果不能居中左短右长,可以指定填充内容,默认以空格填充
    ljust 让字符串在指定的长度左齐,可以指定填充内容,默认以空格填充
    rjust 让字符串在指定的长度右齐,可以指定填充内容,默认以空格填充
    zfill 将字符串填充到指定的长度,不足地方用0从左开始补充
    format 按照顺序,将后面的参数传递给前面的大括号
    strip 默认去除两边的空格,去除内容可以指定
    rstrip 默认去除右边的空格,去除内容可以指定
    lstrip 默认去除左边的空格,去除内容可以指定
    >>> print(string)
    hello world
    >>> print(string.center(15))
      hello world
    >>> print(string.center(15,'*'))
    **hello world**
    >>>
    >>>
    >>> print(string.ljust(15))
    hello world
    >>> print(string.ljust(15,'*'))
    hello world****
    >>> print(string.rjust(15,'*'))
    ****hello world
    >>>
    >>>
    >>> print(string)
    hello world
    >>> print(string.zfill(15))
    0000hello world
    >>>
    >>>
    >>> string = ' hello world '
    >>> print(string)
     hello world
    >>> print(string.strip())
    hello world
    >>> print(string.lstrip())
    hello world
    >>> print(string.rstrip())
     hello world
    >>>
    >>>
    >>> string = "{0} is {1}"
    >>> print(string.format("jrljs","nice"))
    jrljs is nice
    

    8.字符串变形

    参数 描述
    upper 将字符串当中所有的字母转换为大写
    lower 将字符串当中所有的字母转换为小写
    swapcase 将字符串当中所有的字母大小写互换
    title 将字串符当中的单词首字母大写,单词以非字母划分
    capitalize 只有字符串的首字母大写
    expandtabs 把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8,可以试下8,12
    >>> print('hello'.upper())
    HELLO
    >>>
    >>> print('HELLO'.lower())
    hello
    >>>
    >>> print('HH##ZZ'.swapcase())
    hh##zz
    >>> print('*qwe*'.swapcase())
    *QWE*
    >>>
    >>> print('I \t is \t 18'.expandtabs())
    I        is      18
    >>> print('I \t is \t 18'.expandtabs(10))
    I          is        18
    >>> print('I \t is \t 18'.expandtabs(4))
    I    is      18
    
    1. 字符串判断
    参数 描述
    isalnum 判断字符串是否完全由字符或数字组成
    isalpha 判断字符串是否完全由字母组成
    isdigit 判断字符串是否完全由数字组成
    isupper 判断字符串当中的字母是否完全是大写
    islower 判断字符串当中的字母是否完全是小写
    istitle 判断字符串是否满足title格式
    isspace 判断字符串是否完全由空格组成
    startswith 判断字符串的开头字符,也可以截取判断
    endswith 判断字符串的结尾字符,也可以截取判断
    >>> print('123456'.isalnum())
    True
    >>> print('12345ab'.isalnum())
    True
    >>> print('abcde'.isalnum())
    True
    >>>
    >>> print('abcdef'.isalpha())
    True
    >>> print('abcdef#'.isalpha())
    False
    >>> print('abcdef3#'.isalpha())
    False
    >>>
    >>> print("123456".isdigit())
    True
    >>> print("#####".isdigit())
    False
    >>> print("abcdef".isdigit())
    False
    >>>
    >>> print('HELLO'.isupper())
    True
    >>> print('HELLOaabbcc'.isupper())
    False
    >>> print('aabbcc'.isupper())
    False
    >>>
    >>> print('Wo Ow'.istitle())
    True
    >>> print('wO oW'.istitle())
    False
    >>>
    >>> print('  '.isspace())
    True
    >>> print(' Welcome '.isspace())
    False
    >>>
    >>> print('Welcome'.startswith('W'))
    True
    >>> print('Welcome'.startswith('Wel'))
    True
    >>> print('Welcome'.endswith('e'))
    True
    >>> print('Welcome'.endswith('come'))
    True
    >>>
    

    10.字符串编码
    encode 是编码
    decode 是解码

    >>> u = "陆"
    >>> str1 = u.encode('gbk')
    >>> print(str1)
    b'\xc2\xbd'
    >>> print(str2)
    b'jrljs'
    >>> str2 = u.encode('utf-8')
    >>> print(str2)
    b'\xe9\x99\x86'
    >>>
    >>> u1 = str1.decode('gbk')
    >>> print(u1)
    陆
    >>> u2 = str2.decode('utf-8')
    >>> print(u2)
    陆
    

    拓展
    在python中解决编码问题
    由于Python源代码也是一个文本文件,所以,当你的源代码中包含中文的时候,在保存源代码时,就需要务必指定保存为UTF-8编码。当Python解释器读取源代码时,为了让它按UTF-8编码读取,我们通常在文件开头写上这两行(python3默认为utf-8 所以没必要加文档头):
    1、# -- coding: utf-8 --
    2、#coding=utf-8


    练习作业:
    BMI指数(Body Mass Index) 以称身体质量指数
    BMI值计算公式: BMI = 体重(公斤) / 身高的平方(米)
    例如:
    一个人69公斤,身高是173公分
    BMI = 69 / 1.73**2 = 23.05
    标准表:
    BMI < 18.5 体重过轻
    18.5 <= BMI < 24 体重正常
    BMI > 24 体重过重
    要求: 输入身高的体重,打印出BMI的值并打印体重状况

    解答:

    weight = int(input("请输入你的体重(kg):"))
    hight = float(input("请输入你的身高(m):"))
    BMI = weight/pow(high,2)
    if BMI < 18.5:
        print(“体重过轻”)
    elif BMI > 18.5:
        print("体重过重")
    else
        print("体重刚刚好")
    

    相关文章

      网友评论

          本文标题:python数据结构--字符串

          本文链接:https://www.haomeiwen.com/subject/mblnvqtx.html