当前位置: 动力学知识库 > 问答 > 编程问答 >

string - Usage of python bytearray

问题描述:

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'
分享给朋友:
您可能感兴趣的文章:
随机阅读: