what you are probably looking for is StringIO
, which presents a file-like interface to a list of strings, and allows you to extract a single string at the end:
import StringIO
builder = StringIO.StringIO()
builder.write('INSERT INTO ')
builder.write(table_name)
builder.write(' VALUES ')
for row in data_frame.iterrows():
raw_row = row[1].values
builder.write(str(tuple(raw_row)))
insert_string = builder.getvalue()
Although, most python users are happy with using a list directly, as in Rafael's answer. For completeness here's your code translated to that style:
builder = ['INSERT INTO ', table_name, ' VALUES ']
for row in data_frame.iterrows():
raw_row = row[1].values
builder.append(str(tuple(raw_row)))
insert_string = ''.join(builder)
In the odd case that someone viewing this question actually needs a mutable string; I'm sorry to say that there's nothing quite like that, and the solution depends a bit on the exact problem you're trying to solve. If you need a mutable byte string, that's available, builtin, as bytearray
.
>>> b
bytearray(b'xaby')
>>> b[1:3] = b'yz'
>>> b
bytearray(b'xyzy')
>>> b.extend(b'foonly')
>>> b
bytearray(b'xyzyfoonly')
there's no equivalent action for str
, though.