[Tutor] Replace a character by index
srilyk at gmail.com
Thu Jul 16 10:29:49 CEST 2009
My question is more about style/timing than anything else.
In my program I'm taking a word and generating "blanks" in that word. For
example, the word cat could generate:
I have two different ways I can put _ in the word:
word = 'cat'
''.join(list(word) = '_')
# I'm not using a constant, but randomly generating where the blank appears
word[:1] + '_' + word[1+1:]
So, when I use the timeit module I get these results:
In : timeit.Timer("''.join(list('foo'))").timeit()
In : timeit.Timer("'foo'[:2]+'_'+'foo'[2+1:]").timeit()
Quite a significant difference.
So my question(s): Which method should I use/is more pythonic? Which method
do you/have you used? And the ubiquitous 'Why?'
Normally I would lean towards the first method because reassigning a value
in a list seems more natural than string concatenation. In this particular
application I'm not exactly worried about performance - on even an archaic
computer I don't think one would notice.
TIA for your input,
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor