• python -- join()


    python -- join()



    月似当时,人似当时否?


    在 python 中,一共有两个 join 方法,一个是 str.join(),另一个是 os.path.join() ,这里只了解前一种


    str.join(iterable)

    官方文档
    Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

    简单来讲,就是将可迭代对象中的元素以 str 为分隔符拼接返回,但是这些元素必须为 String 类型,不然会报错

    # 报错
    >>> l = [1,2,3]
    >>> " ".join(l)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: sequence item 0: expected str instance, int found
    
    # 对 list 拼接
    >>> l = ["hello","pinsily"]
    >>> " ".join(l)
    'hello pinsily'
    
    # 对 string 拼接
    >>> s = "hello pinsily"
    >>> ":".join(s)
    'h:e:l:l:o: :p:i:n:s:i:l:y'
    
    # 对元组拼接
    >>> t = ("hello","pinsily")
    >>> " ".join(t)
    'hello pinsily'
    
    # 对字典拼接
    >>> d = {"hello":"1","pinsily":"2","and":"3","world":"4"}
    >>> " ".join(d)
    'hello pinsily and world'
    
    
    

    :当要使用大量的字符串拼接时,尽量避免 + 操作,这样会产生大量的临时变量,占据内存,可以先将其拼接到 list 中,然后使用 join 方法


  • 相关阅读:
    【洛谷P1558】色板游戏
    【SCOI2010】序列操作
    Windows下MySQL下载安装、配置与使用
    Redis和MySQL数据同步及Redis使用场景
    python的设计模式之MVC模式
    python 面试真题
    python调用C语言
    一次跨域请求出现 OPTIONS 请求的问题及解决方法
    服务器宕机问题
    页面静态化
  • 原文地址:https://www.cnblogs.com/pinsily/p/7904191.html
Copyright © 2020-2023  润新知