• 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,就要做到‘活到老学到老’!

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

  • 相关阅读:
    安卓强制杀死进程的几种方法收集汇总
    android studio :Timeout waiting to lock daemon addresses registry
    20170825遇到的问题
    百度地图的那些坑
    静态内部类的加载方式
    C#文本转语音并保存wav和MP3文件
    一个ASPX页面的生命周期?
    用SQL替换最后一个指定字符后面的所有字符
    用SQL求1到N的质数和
    谈谈托管代码、IL、CLR、ISAPI?
  • 原文地址:https://www.cnblogs.com/twoo/p/11642712.html
Copyright © 2020-2023  润新知