zoukankan      html  css  js  c++  java
  • python中字符串常见操作(二)

    # 可迭代对象有:字典,列表,元组,字符串,集合

    str1 = '192.168.1.1'
    str2 = 'as df gh jk'
    str3 = '小李子'
    str4 = ['aa','bb','cc']
    str5 = '$$$192.168.1.1&&&'
    str6 = '	
    mysql	
    '
    b = '='

    # .join:把可迭代对象转化为字符串
    # 字典只循环key
    # 只能合并里边是字符串的可迭代对象

    >>> res = ''.join(['1','2','3'])
    >>> print(res)
    123
    >>> res = ''.join({'a':12,'b':22,'c':33})
    >>> print(res)
    abc
    >>> res = ''.join(('1','2','3'))
    >>> print(res)
    123
    >>> res = ''.join([1,2,3])
    >>> print(res)
    res = ''.join([1,2,3])
    TypeError: sequence item 0: expected str instance, int found
    >>> res = b.join(str4)
    >>> print(res)
    aa=bb=cc

    # splite:是可以把字符串分割成列表;rsplit

    >>> res = str1.split('.',1)
    >>> print(res)
    ['192', '168.1.1']
    >>> res = str1.split('.')
    >>> print(res)
    ['192', '168', '1', '1']
    >>> res = str2.split('空格')
    >>> print(res)
    ['as', 'df', 'gh', 'jk']

    面试题:
    test = "aa ks js fa ka ",除去 和空格?
    result = test.split()

    # replace:替换字符串

    >>> res = str1.replace('.','|',1)
    >>> print(res)
    192|168.1.1
    >>> res = str1.replace('.','|')
    >>> print(res)
    192|168|1|1

    # strip:去除字符串两边指定字符,(一般用来除去两边特殊字符或格式)
    # rstrip(从右边开始),lstrip(从左边开始)

    >>> res = str5.strip('$&')
    >>> print(res)
    192.168.1.1
    >>> res = str5.rstrip('$&')
    >>> print(res)
    $$$192.168.1.1
    >>> res = str5.lstrip('$&')
    >>> print(res)
    192.168.1.1&&&
    >>> res = str6.lstrip()
    >>> print(res)
    mysql

    # utf8格式的字符编码:1个中文占3个字节,生僻字会占用更多
    # gbk格式的字符编码:1个中文占2个字节
    # 用什么字符编码写入就需要用什么字符编码格式打开
    #encode和decode分别指编码和解码

    >>> res = str1.encode('utf-8')
    >>> print(res)
    b'$$$192.168.1.1&&&'
    >>> res = str6.encode('utf-8')
    >>> print(res)
    b'	
    mysql	
    '
    >>> res = str3.encode('utf-8')
    >>> print(res)
    b'xe5xb0x8fxe6x9dx8exe5xadx90'
    >>> res = str3.encode('utf-8')
    >>> result = res.decode('utf-8')
    >>> print(result)
    小李子

    #字符串可以拼接:相加,可以与数字相乘
    # a = '123'
    # b = 'abc'
    # print(a+b)

    作者:无荨

    -------------------------------------------

    个性签名:学IT,就要做到‘活到老学到老’!

    如果觉得这篇文章对你有小小的帮助的话,别忘记点个“推荐”哦!

  • 相关阅读:
    C实现类封装、继承、多态
    运算符重载详解
    类定义 对象数组
    Install KVM Hypervisor on arrch64 Linux Server
    Failed to load package MonoAndroidDesignerPackage
    C# is和as操作符
    C#中out和ref之间的区别
    C#中 const 和 readonly 的区别
    C#版本和.NET版本以及VS版本的对应关系
    各类纤程/协程使用比较
  • 原文地址:https://www.cnblogs.com/twoo/p/11642712.html
Copyright © 2011-2022 走看看