• Python学习二:字符串


    一、字符串编码转换

    1.1 使用encode()方法编码

    str=encode([encoding="utf-8]"[,error="strict"])
    默认是utf-8 如果想用简体中文也可以用gb2312
    strict:遇到错误的时候就抛出异常
    也可以是ignore(忽视) 还可以是replace
    
    
    if __name__ == '__main__':
        value='你好,我是代码浪人,浪里浪'
        byte=value.encode('GBK')
        print(value)
        print(byte)
    》》》
    你好,我是代码浪人,浪里浪
    b'\xc4\xe3\xba\xc3\xa3\xac\xce\xd2\xca\xc7\xb4\xfa\xc2\xeb\xc0\xcb\xc8\xcb\xa3\xac\xc0\xcb\xc0\xef\xc0\xcb'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    1.2 使用encode()方法解码

    str=decode([encoding="utf-8]"[,error="strict"])
    默认是utf-8 如果想用简体中文也可以用gb2312
    strict:遇到错误的时候就抛出异常
    也可以是ignore(忽视) 还可以是replace
    
    
    
    if __name__ == '__main__':
        value='你好,我是代码浪人,浪里浪'
        byte=value.encode('GBK')
        print(value)
        print(byte)
        print(byte.decode('GBK'))
    
    》》》
    
    你好,我是代码浪人,浪里浪
    b'\xc4\xe3\xba\xc3\xa3\xac\xce\xd2\xca\xc7\xb4\xfa\xc2\xeb\xc0\xcb\xc8\xcb\xa3\xac\xc0\xcb\xc0\xef\xc0\xcb'
    你好,我是代码浪人,浪里浪
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    二、字符串常规操作

    2.1 拼接字符串

    直接使用加号(同类型,不同类型会报错)

    if __name__ == '__main__':
        value1="你好"
        value2=123
        print(value1+value2)
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    2.2 计算字符串的长度

    汉字在GBK/GB2312编码占2个字节
    在UTF-8.uncode占3个字节(或者4个字节)

    计算长度提供len(string) 函数计算方法

    
    if __name__ == '__main__':
        value1="你好"
        print(len(value1))
        print(len(value1.encode('GBK')))
    》》》
    2 
    4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.3 截取字符串

    string[start🔚step]
    start:开始位置,默认为0
    end:结束位置,不包含
    step:步长,默认为1

    if __name__ == '__main__':
        value1="你好345678"
        print(value1[2:])
        print(value1[:2])
        print(value1[0:8:2])
    
    》》》
    345678
    你好
    你357
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.4 分割、合并字符串

    分割

    str.split(sep,maxsplit)
    str:要分割的字符串
    sep:指定分隔符,默认为None
    maxsplit: 可选参数,默认为-1-> 分割次数

    合并

    strnew=str.join(iterable)
    strnew:新的字符串
    string:用于合并时候的分隔符号
    iterable:可迭代对象,将迭代对象中的所有元素按照分个字符串进行拼接

    
      list_str=['我','爱','你']
        list_new='*'.join(list_str)
        print(list_new)
    》》》
    我*爱*你
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.5 检索字符串

    方法一:count()计算数量

    str.count(sub[,start[,end]])

    str检索的字符串
    sub:需要检索的子字符串
    start:开始位置
    end:结束位置

    str='123456'
    print(str.count(6))
    》》》
    1
    
    • 1
    • 2
    • 3
    • 4

    方法二:find()计算位置

    str.find(sub[,start[,end]])

    str检索的字符串
    sub:需要检索的子字符串
    start:开始位置
    end:结束位置

    str='123456'
    print(str.find(6))
    》》》
    5
    
    • 1
    • 2
    • 3
    • 4

    方法三:in 判断位置

    if __name__ == '__main__':
        list_str=['我','爱','你']
        print('爱' in list_str)
    》》》
    True
    
    • 1
    • 2
    • 3
    • 4
    • 5

    方法四:index()方法和find一样,只不过是不存在出抛出异常

    str.index(sub[,start[,end]])

    str检索的字符串
    sub:需要检索的子字符串
    start:开始位置
    end:结束位置

    方法五:startswitch()方法 返回Ture或者False

    str.startswitch(prefix[,start[,end]])

    str检索的字符串
    prefix:需要检索的子字符串
    start:开始位置
    end:结束位置

    if __name__ == '__main__':
        list_str=['我','爱','你']
         print(list_str.startswitch('我'))
    》》》
    True
    
    • 1
    • 2
    • 3
    • 4
    • 5

    方法六:endswitch()方法 返回Ture或者False

    str.endswitch(prefix[,start[,end]])

    str检索的字符串
    prefix:需要检索的子字符串
    start:开始位置
    end:结束位置

    
    if __name__ == '__main__':
        list_str=['我','爱','你']
        print(list_str.endswitch('你'))
    》》》
    True
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.6 字母的大小写转化

    大写转小写lower()方法,小写转大写upper()

    if __name__ == '__main__':
        str='ABC'
        print(str.lower())
        str='abc'
        print(str.upper())
    》》》
    abc
    ABC
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.7 去除字符串中的空字符串和特殊字符串

    方法一:strip()

    str.strip([char])//默认为是去除首尾空字符和特殊字符串,char是可选,可指定多个

    方法二:lstrip()

    str.lstrip([char])//默认为是去除左边空字符和特殊字符串,char是可选,可指定多个,

    方法三:rstrip()

    str.rstrip([char])//默认为是去除右边空字符和特殊字符串,char是可选,可指定多个

    2.8 格式化字符串

    1.使用% 操作符号

    Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。

    print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
    
    我叫 小明 今年 10 岁!
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述
    格式化操作符辅助指令:
    在这里插入图片描述

    2.format 格式化函数

    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'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    也可以设置参数

    # -*- coding: UTF-8 -*-
     
    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    也可以向 str.format() 传入对象:

    
     
    class AssignValue(object):
        def __init__(self, value):
            self.value = value
    my_value = AssignValue(6)
    print('value 为: {0.value}'.format(my_value))  # "0" 是可选的
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    数字

    >>> print("{:.2f}".format(3.1415926))
    3.14
    
    • 1
    • 2

    在这里插入图片描述
    此外我们可以使用大括号 {} 来转义大括号,如下实例:

     
    print ("{} 对应的位置是 {{0}}".format("runoob"))
    》》》
    runoob 对应的位置是 {0}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    echarts统计图表
    【Leetcode】215. 数组中的第K个最大元素
    通过 Helm Chart 部署 Easysearch
    SpringSecurity入门
    MySQL Server 5.5 软件和安装配置教程
    JavaScript实现鼠标经过图标的浮动
    【Transformers】第 9 章:跨语言和多语言语言建模
    加速度jsudo:小企业会遇到哪些瓶颈期?
    如何选择适合的PoE交换机?
    Git 常用命令
  • 原文地址:https://blog.csdn.net/huiguo_/article/details/125531438