问题描述:

I was wondering whether using bytearray for constructing a string like.

def build_string(pairs):

data = ''

for key, value in pairs.iteritems():

data = data + '\r\n' + '%s:%s' % (key, value)

data = data + '\r\n\r\n'

return data

would be slower than.

def build_string(pairs):

data = bytearray()

for key, value in pairs.iteritems():

data.extend('%s:%s\r\n' % (key, value))

data.extend('\r\n')

return data

网友答案:

You should just use str.join()

You generally shouldn't need to include the carriage return (\r). Python has universal newline support. It will use the correct line ending for the OS.

return '\n'.join('{0}:{1}'.format(k, v) for k, v in pairs.iteritems()) + '\n\n'
相关阅读:
Top