美文网首页
python 字符串连接

python 字符串连接

作者: robertzhai | 来源:发表于2023-05-21 16:29 被阅读0次

    Plus Operator (+) 低效

    >>> "Hello, " + "Pythonista!"
    'Hello, Pythonista!'
    

    String concatenation using+and its augmented variation,+=`, can be handy when you only need to concatenate a few strings. However, these operators aren’t an efficient choice for joining many strings into a single one. Why? Python strings are immutable, so you can’t change their value in place. Therefore, every time you use a concatenation operator, you’re creating a new string object.

    • This behavior implies extra memory consumption and processing time because creating a new string uses both resources. So, the concatenation will be costly in two dimensions: memory consumption and execution time

    join() 高效

    >>> " ".join(["Hello,", "World!", "I", "am", "a", "Pythonista!"])
    'Hello, World! I am a Pythonista!'
    
    >>> numbers = [1, 2, 3, 4, 5]
    
    >>> "; ".join(str(number) for number in numbers)
    '1; 2; 3; 4; 5'
    
    

    StringIO 高效

    >>> from io import StringIO
    
    >>> words = ["Hello,", "World!", "I", "am", "a", "Pythonista!"]
    
    >>> sentence = StringIO()
    >>> sentence.write(words[0])
    6
    >>> for word in words[1:]:
    ...     sentence.write(" " + word)
    ...
    7
    2
    3
    2
    12
    >>> sentence.getvalue()
    

    ref

    相关文章

      网友评论

          本文标题:python 字符串连接

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