• Python_base_字符串、切片


    一、字符串查找和替换

    hello_str="hello word"


    #判断是否以指定字符串开始
    print(hello_str.startswith("hello")) True

    #判断是否以指定字符串结束
    print(hello_str.endswith("word")) True

    #查找指定字符串
    print(hello_str.find("llo")) 2
    print(hello_str.find("lloc")) -1 #index指定的字符串会报错,find指定的字符串不存在会返回-1

    #替换字符串
    #replace方法执行完成后,会返回一个新的字符串,不会修改原有字符串的内容
    print(hello_str.replace("hello","python")) python word

    print(hello_str) hello word

    二、去除空白字符串
    pome=["	
    慈母手中线",
    "游子身上衣",
    "临行密密缝",
    "意恐迟迟归"]

    for pome_str in pome:

    print("|%s|" %pome_str.strip().center(10))
    #先使用strip方法去除字符串中的空白字符

    #再用center方法居中显示文本


    输出结果:

    | 慈母手中线 |
    | 游子身上衣 |
    | 临行密密缝 |
    | 意恐迟迟归 |

    三、字符串的切片
    num_str="0123456789"

    # 截取从2到5位置的字符串
    print(num_str[2:6] 2345


    # 截取从2 到 末尾的字符串

    print(num_str[2:]) 23456789

    #截取从开始到5的字符串
    print(num_str[:6]) 012345

    #截取完整的字符串
    print(num_str[:]) 0123456789

    #从开始位置,每隔一个字符截取字符串
    print(num_str[: :2]) 02468

    #从索引1开始,每隔一个取一个
    print(num_str[1: :2]) 13579


    #截取从2 到 末尾-1的字符串
    print(num_str[2:-1]) 2345678

    # 截取字符串末尾2个字符
    print(num_str[-2:]) 89

    #字符串的逆序
    print(num_str[-1: :-1]) # 步长为-1 表示切片从右向左切
    print(num_str[: :-1]) 9876543210

    四、字符串的大小写转换


     
  • 相关阅读:
    100——第9例
    100——第8例
    100——第7例
    POJ
    POJ
    POJ
    Egyptian Collegiate Programming Contest 2017 (ACM ECPC 2017)
    SCUT
    SCUT
    SCUT
  • 原文地址:https://www.cnblogs.com/tianpin/p/10116923.html
Copyright © 2020-2023  润新知