python 字符串连接

2023-05-21  本文已影响0人  robertzhai

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.

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

上一篇 下一篇

猜你喜欢

热点阅读