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))

  • 相关阅读:
    shell脚本编程练习
    linux中()、[]、{}、(())、[[]]等各种括号的使用
    Linux Shell 变量自加
    while read line [linux] shell 学习
    踢出某正在访问的用户||永久禁止某IP访问
    linux设置 自定义脚本开机启动
    syntax error: unexpected end of file完美解决方案
    Linux利用nc命令脚本批量检测服务器指定端口是否开放
    41-贪心算法
    38-动态规划
  • 原文地址:https://www.cnblogs.com/wwyydd/p/14265620.html
Copyright © 2011-2022 走看看