Concatenating Strings

Travis Griggs travisgriggs at
Thu Apr 9 20:29:51 CEST 2015

I was doing some maintenance now on a script of mine… I noticed that I compose strings in this little 54 line file multipole times using the + operator. I was prototyping at the time I wrote it and it was quick and easy. I don’t really care for the way they read. Here’s 3 examples:

    if k + ‘_@‘ in documents:

    timeKey = k + ‘_@‘

    historyKey = thingID + ‘_’ + k

I’m curious where others lean stylistically with this kind of thing. I see *at least* 2 other alternatives:

Use join():

    if ‘’.join((k, ‘_@‘)) in documents:

    timeKey = ‘’.join((k, ‘_@‘))

    historyKey = ‘_’.join((thingID, k))

I don’t really like any of these. Maybe the 3rd, but I’d really rather see the pattern out. I also don’t like that I have to double the parens just to get a single arg joinable tuple for join()

Use format():

    if ‘{}_@‘.format(k) in documents:

    timeKey =  ‘{}_@‘.format(k)

    historyKey = ‘{}_{}’.format(thingID, k)

I like these because you see a template of the values. But its still longer than just using +.

So I’m curious from those more seasoned, when they tend to use which approaches, and why.

More information about the Python-list mailing list