Is there anything in Python like Java's StringBuffer
? Since strings are immutable in Python too, editing them in loops would be inefficient.
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- streaming md5sum of contents of a large remote tar
- How to maintain order of key-value in DataFrame sa
this link might be useful for concatenation in python
http://pythonadventures.wordpress.com/2010/09/27/stringbuilder/
example from above link:
Efficient String Concatenation in Python is a rather old article and its main statement that the naive concatenation is far slower than joining is not valid anymore, because this part has been optimized in CPython since then:
I've adapted their code a bit and got the following results on my machine:
Results:
Conclusions:
join
still wins over concat, but marginallyPerhaps use a bytearray:
The appeal of using a bytearray is its memory-efficiency and convenient syntax. It can also be faster than using a temporary list:
Note that much of the difference in speed is attributable to the creation of the container:
Just a test I run on python 3.6.2 showing that "join" still win BIG!
And the output was:
The previously provided answers are almost always best. However, sometimes the string is built up across many method calls and/or loops, so it's not necessarily natural to build up a list of lines and then join them. And since there's no guarantee you are using CPython or that CPython's optimization will apply, then another approach is to just use print!
Here's an example helper class, although the helper class is trivial and probably unnecessary, it serves to illustrate the approach (Python 3):
Depends on what you want to do. If you want a mutable sequence, the builtin
list
type is your friend, and going from str to list and back is as simple as:If you want to build a large string using a for loop, the pythonic way is usually to build a list of strings then join them together with the proper separator (linebreak or whatever).
Else you can also use some text template system, or a parser or whatever specialized tool is the most appropriate for the job.