zoukankan      html  css  js  c++  java
  • 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 方法


  • 相关阅读:
    http协议
    三次握手四次挥手的原理
    mmap
    I/O多路复用之poll
    I/O多路转接之select
    自旋锁、文件锁、大内核锁
    网络基础(一)
    线程同步之(信号量)
    进程与线程的简单理解
    内存溢出——程序员必备网站
  • 原文地址:https://www.cnblogs.com/pinsily/p/7904191.html
Copyright © 2011-2022 走看看