美文网首页
第六章 字符串

第六章 字符串

作者: 你笑的那么美丶 | 来源:发表于2019-03-20 20:32 被阅读0次

    创建

    s1 = 'shark'
    s2 = "shark"
    s3 = """hello shark"""
    s4 = '''hello shark'''
    s5 = """hello
    shark
    """
    
    

    简单操作

    \ 转义符

    testimony = 'This shirt doesn\'t fit me'
    
    
    words = 'hello \nworld'
    
    

    +拼接

    print('hello' + 'world')
    
    

    不可以用 字符串和 一个非字符串类型的对象相加

    'number' + 0   # 这是错误的
    
    

    * 复制

    print('*' * 20)
    print('shark' * 20)
    
    

    字符串 和 0 或者 负数相乘,会得到一个空字符串

    In [76]: 'hey' * 0
    Out[76]: ''
    
    In [77]: 'hey' * -3
    Out[77]: ''
    
    

    进阶操作

    认识 Python 中第一个数据结构 序列类型

    • 存放的数据,在其内是有序的,内部的数据是可以通过在其

      内部所处的位置进行访问等操作。

    字符串型就是 python 序列类型的数据结构中的一种,本质是

    字符序列

    序列类型的特点

    • 序列里的每个数据被称为序列的一个元素

    • 元素在序列里都是有个自己的位置的,这个位置被称为索引或

      者叫偏移量,也有叫下标的

    • 下标偏移量从 0 开始到序列整个元素的个数减去1结束

    • 序列中的每一个元素可以通过这个元素的偏移量(索引)来获取到

    • 而多个元素需要用切片的操作来获取到

    s1 = "shark"
    
    
    image
    获取元素
    # 获取单个元素
    s1[0]
    s1[3]
    s1[-1]
    
    

    切片

    image
    # 使用切片获取多个元素
    s1[0:2]
    
    

    下面这样的操作,是的不到我的

    s1[-1:-3]
    
    
    # 获取字符串的长度,包含空格和换行符
    len(s1)
    
    
    利用字符串对象的方法

    split

    url = 'www.qfedu.com 千锋官网'
    url.split()
    
    li = url.split('.')
    
    host, *_ = url.split('.', 1)
    
    

    rsplit 从右向左分割

    url = 'www.qfedu.com'
    url2 = url.rsplit('.', 1)
    
    

    replace 替换

    url = 'www.qfedu.com'
    url2 = url.replace('.', '_')
    
    

    strip 移除两端的空格

    s = ' hello   '
    s2 = s.strip()
    
    inp = input(">:").strip()
    
    
    s = "symbol=BCHBTC;baseCoin=BCH;quoteCoin=BTC;"
    
    s_list = s.split(';')
    # print(s_list)
    # ['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC', '']
    
    

    startswith 判断字符串以什么为开头

    s = 'hello world'
    if s.startswith('h'):
        print(s)
    
    

    endswith 判断字符串以什么为结尾

    s = 'hello world'
    if s.endswith('d'):
        print(s)
    
    

    index 获取一个元素在字符串中的索引号

    s = 'hello world'
    idx = s.index('l')
    
    
    image image image

    交互输入

    image

    相关文章

      网友评论

          本文标题:第六章 字符串

          本文链接:https://www.haomeiwen.com/subject/qqqxvqtx.html