zoukankan      html  css  js  c++  java
  • Python 知识要点:字符串

    字符串是一个有序的字符的集合,用来储存和表现基于文本的信息。

    常见的是单引号和双引号形式,两种形式同样有效可以互换。

    【字符串判断方法】

    复制代码

    1.判断空白字符

    space_str = " "
    print(space_str.isspace())

    2.判断字符串中是否只包含数字

    1>三个方法都不能判断小数

    2>判断:纯数字 -> +unicode -> +中文数字

    num_str = ""
    print(num_str)
    print(num_str.isdecimal())
    print(num_str.isdigit())
    print(num_str.isnumeric())
    复制代码

    【字符串查找替换】

    复制代码
    hi_str = "hi world"

    1.判断是否以指定的字符串开始

    print(hi_str.startswith("h"))

    2.判断是否以指定字符串结束

    print(hi_str.endswith("i"))

    3.查找指定字符串

    index同样可以查找制定的字符串在大字符串中的索引

    print(hi_str.find("i"))

    如果指定的字符串不存在,index会报错,find返回-1

    print(hi_str.find("12"))

    4.替换字符串

    print(hi_str.replace("world", "python"))
    print(hi_str)
    复制代码

    【字符串拆分和连接】

    复制代码

    1.将字符串中的空白字符全部去除

    2.再用""作为分隔符,拼接成一个整齐的字符串

    poem = "静夜思 李白 床前明月光 疑是地上霜"
    print(poem)

    1.拆分

    r = poem.split()
    print(r)

    2.合并

    print(" ".join(r))
    复制代码

    【字符串文本对齐】

    复制代码

    居中对齐文本,去除空白字符

    poem = [" 静夜思",
    "李白",
    "床前明月光",
    "疑是地上霜"]
    print(type(poem))
    for poem_str in poem:
    print("!%s!" % poem_str.strip().center(15))

  • 相关阅读:
    java 线程开启 中断
    手写迷你版hashmap
    基于状态机的乐观锁
    Python清空指定文件夹下所有文件的方法
    Python
    python+selenium配置Edge浏览器
    python+selenium怎么获取ul下面最后一个li或ul中有多少个li
    Python Selenium 笔记
    XPath定位时,使用文本的方法小技巧。
    python yield返回多个值
  • 原文地址:https://www.cnblogs.com/wwyydd/p/14265620.html
Copyright © 2011-2022 走看看