zoukankan      html  css  js  c++  java
  • python学习笔记:(六)str(字符串)常用方法

    注意点:

      1、字符串是不可变的;

      2%格式化操作符:左侧放置字符串,右侧放置希望被格式化的值。

      对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符

      以Unicode表示的str通过encode()方法可以编码为指定的bytes

    常用方法

    1substitute()

      替换指定变量的值(替换全部)

    1 #substitute
    2 from string import Template
    3 s=Template('$x,glorious $x!')
    4 print(s.substitute(x='stone'))

      替换部分

    1 m=Template("This is s${a}one")
    2 print(m.substitute(a='t'))

    2find()

      在一个比较长的字符串中查找子串,返回子串所在位置的最左端索引

    1 str01="chinachinachinachinachina"
    2 print(str01.find('na'))

    3join()

      用来连接序列的元素

    1 #join
    2 dir1='0','1','2','3'
    3 
    4 print('/'.join(dir1))

    4lower()

      返回小写字母

    1 #lower
    2 str001='WERWERSDFsdfWERWER123'
    3 print(str001.lower())

    5title()

      以标题的方式显示

    1 #title
    2 str001=" tHis is mytitle"
    3 print(str001.title())

    6capitalize()

    1 #capitalize
    2 str001=" tHis is Mytitle"
    3 print(str001.capitalize())

    7replace()

      替换

    #replace:替换
    str001="this  is mytitle"
    print(str001.replace('is','aha'))
    

    8split()

      将字符串分割成序列

    1 #split
    2 str001="this is mytitle"
    3 print(str001.split())

    9strip()

      返回去除两侧(不包含内部)空格的字符串

    1 #strip
    2 str001=" this is mytitle    "
    3 str002="**this is mytitle**"
    4 print(str001)
    5 print(str001.strip())
    6 print(str002)
    7 print(str002.strip("*"))

    10translate()

      替换,只处理单个字符

    1 #translate
    2 str001="a"
    3 print(str001.translate('h')) 
  • 相关阅读:
    java之正则表达式
    mysql之自定义函数
    mysql之replace into与 insert into duplicat key for update
    mysql之命令行导入导出
    Echarts修改legend样式
    ubuntu出现 E: Sub-process /usr/bin/dpkg returned an error code
    ubuntu总是提是E: 不能满足依赖关系。不妨试一下 -f 选项
    ubuntu安装和查看已安装软件
    放爬虫nginx
    nginx日志切割
  • 原文地址:https://www.cnblogs.com/smallstone2018/p/10045490.html
Copyright © 2011-2022 走看看