delimiting text file??

Thomas A. Bryan tbryan at python.net
Thu Oct 14 16:33:38 EDT 1999


Gerrit Holl wrote:
> 
> Aahz Maruch:
> > In article <3804F889.30739C22 at bruer.org>, Jim Bruer  <jim at bruer.org> wrote:
> >
> > >How do you insert a delimiter into a string at a given position?
> > >
> > >Tried "f.insert(i,x)" then realized this is for mutable sequences.This
> > >is so stupid I'm embarrassed to ask.
> >
> > delimitedString = string[:x] + "," + string[x:]
> >
> > That's a rather lame way to do it; as you learn more about Python,
> > you'll come across better ways.
> 
> Is it? I think I've learned more about Python than Jim has (already finished
> Learning python, and I'm waiting for Programming TkInter with Python now),
> but I don't know a better way than this?

The problem is that
 string[:x] + ',' + string[x:]
creates at least two temporary objects (string[:x] and string[x:])
and just to add in this one character.  It's a decent way to insert 
one character into a string, but the overhead for "slicing" the 
string and concatenating it again would probably slow down any 
app that calls such an operation many times on the same string.
(To know for sure, one would have to implement the application 
in multiple ways and then time the performance.)

For example, consider
s = """some very long string...probably 
 spanning multiple lines"""
s = s[:2] + ',' + s[2:]
s = s[:4] + ',' + s[4:]
s = s[:6] + ',' + s[6:]
s = s[:8] + ',' + s[8:]

Think of all of the objects being created and destroyed by Python.
There's the original string for s, 4*2=8 substrings on the right
side of the equals sign formed by concatenation, and the four 
resulting strings that are assigned to s.  In fact, I think there's
even a temporary string created to hold the intermediate results 
of the addition (s[:2] + ',').

The other problem with such a solution is that if I compute the 
indices where I want the commas first (on the original string s), 
then the indices will need to be adjusted as I add characters to 
the string.

A different solution (the essence of another reply to this post)
is to split the string up into a list based on some criterion and
then rejoin the list elements with a comma.

For example,
import string
s = "one two three four"
sList = string.split(s)
s = string.join(sList,',')

Of course, then the hard part becomes splitting up the string in 
the first place, but I'm assuming that that part is already done 
if the poster just needs to insert a comma at a given index.

---Tom




More information about the Python-list mailing list