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()
网友评论