Reputation: 595
Something like
sentence.replace(*, "newword")
(which doesn't work, btw)
Let's say
sentence = "hello world"
return sentence.replace(*, "newworld")
should return "newword newword"
Upvotes: 1
Views: 105
Reputation: 7678
If you care about speed, just crafting the string manually seems to be twice as fast:
In [8]: import re
In [9]: sentence = "hello world this is my sentence"
In [10]: nonspace = re.compile('[^\s]+')
In [11]: %timeit re.sub(nonspace, 'newword', sentence)
100000 loops, best of 3: 6.28 µs per loop
In [12]: %timeit ' '.join('newword' for _ in xrange(len(sentence.split())))
100000 loops, best of 3: 2.52 µs per loop
In [13]: sentence *= 40 # Make the sentence longer
In [14]: %timeit re.sub(nonspace, 'newword', sentence)
10000 loops, best of 3: 70.6 µs per loop
In [15]: %timeit ' '.join('newword' for _ in xrange(len(sentence.split())))
10000 loops, best of 3: 30.2 µs per loop
And join
is actually faster when you hand it a list, so ' '.join(['newword' for _ in xrange(len(sentence.split()))])
should result in some performance improvements (it caches the result in my informal %timeit
tests, so I didn't include it)
Upvotes: 0
Reputation: 76557
Since you aren't going to be replacing a specific word, str.replace()
won't really support any kind of pattern-matching.
However, you could use the re.sub()
function that will allow you to pass in a Regular Expression that would match everything and replace it :
import re
# Replace each series of non-space characters [^\s]+ with "newword"
sentence = re.sub('[^\s]+','newword',sentence)
Example
You can find a complete interactive example of this here and demonstrated below :
Upvotes: 5
Reputation: 359
What you're looking for is a word replace. So instead of string.replace which replaces characters, you want something that will replace all words.
>>> sentence = "hello world this is my sentence"
>>> " ".join(["newword"] * len(sentence.split()))
'newword newword newword newword newword newword'
In the above case we're spiting the sentence into a list of it's words and simple making another list of words "newword" of the same length. Finally we're joining the new words together with the " " character in between them
Upvotes: 0