Python equivalent of Java StringBuffer?

后端 未结 8 1308
半阙折子戏
半阙折子戏 2020-12-04 21:10

Is there anything in Python like Java\'s StringBuffer? Since strings are immutable in Python too, editing them in loops would be inefficient.

8条回答
  •  猫巷女王i
    2020-12-04 21:17

    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, an alternative 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):

    import io
    
    class StringBuilder(object):
    
        def __init__(self):
            self._stringio = io.StringIO()
        
        def __str__(self):
            return self._stringio.getvalue()
        
        def append(self, *objects, sep=' ', end=''):
            print(*objects, sep=sep, end=end, file=self._stringio)
    
    sb = StringBuilder()
    sb.append('a')
    sb.append('b', end='\n')
    sb.append('c', 'd', sep=',', end='\n')
    print(sb)  # 'ab\nc,d\n'
    

提交回复
热议问题