473,732 Members | 2,214 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

best way to replace first word in string?

I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one

Oct 20 '05 #1
20 11320
There is a "gotcha" on this:

How do you define "word"? (e.g. can the
first word be followed by space, comma, period,
or other punctuation or is it always a space).

If it is always a space then this will be pretty
"efficient" .

string="aa to become"
firstword, restwords=s.spl it(' ',1)
newstring="/%s/ %s" % (firstword, restwords)

I'm sure the regular expression gurus here can come
up with something if it can be followed by other than
a space.

-Larry Bates
ha*****@gmail.c om wrote:
I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one

Oct 20 '05 #2
"ha*****@gmail. com" <ha*****@gmail. com> writes:
I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one


Assuming you know the whitespace will be spaces, I like find:

new = "/aa/" + old[old.find(' '):]

As for efficiency - I suggest you investigate the timeit module, and
do some tests on data representative of what you're actaully going to
be using.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Oct 20 '05 #3
On Oct 20, ha*****@gmail.c om wrote:
I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one


Of course there are many ways to skin this cat; here are some trials.
The timeit module is useful for comparison (and I think I'm using it
correctly :-). I thought that string concatenation was rather
expensive, so its being faster than %-formatting surprised me a bit:

$ python -mtimeit '
res = "/%s/ %s"% tuple("a b c".split(" ", 1))'
100000 loops, best of 3: 3.87 usec per loop

$ python -mtimeit '
b,e = "a b c".split(" ", 1); res = "/"+b+"/ "+e'
100000 loops, best of 3: 2.78 usec per loop

$ python -mtimeit '
"/"+"a b c".replace(" ", "/ ", 1)'
100000 loops, best of 3: 2.32 usec per loop

$ python -mtimeit '
"/%s" % ("a b c".replace(" ", "/ ", 1))'
100000 loops, best of 3: 2.83 usec per loop

$ python -mtimeit '
"a b c".replace(" ", "/", 1).replace(" ", "/ ", 1)'
100000 loops, best of 3: 3.51 usec per loop

There are possibly better ways to do this with strings.

And the regex is comparatively slow, though I'm not confident this one
is optimally written:

$ python -mtimeit -s'import re' '
re.sub(r"^(\w*) ", r"/\1/", "a b c")'
10000 loops, best of 3: 44.1 usec per loop

You'll probably want to experiment with longer strings if a test like
"a b c" is not representative of your typical input.

--
_ _ ___
|V|icah |- lliott http://micah.elliott.name md*@micah.ellio tt.name
" " """
Oct 20 '05 #4
Micah Elliott wrote:
And the regex is comparatively slow, though I'm not confident this one
is optimally written:

$ python -mtimeit -s'import re' '
re.sub(r"^(\w*) ", r"/\1/", "a b c")'
10000 loops, best of 3: 44.1 usec per loop


the above has to look the pattern up in the compilation cache for each loop,
and it also has to parse the template string. precompiling the pattern and
using a callback instead of a template string can speed things up somewhat:

timeit -s"import re; sub = re.compile(r'^( \w*)').sub"
"sub(lambda x: '/%s/' % x.groups(), 'a b c')"

(but the replace solutions should be faster anyway; it's not free to prepare
for a RE match, and sub uses the same split/join implementation as replace...)

</F>

Oct 20 '05 #5
On Thu, 20 Oct 2005 08:26:43 -0700, ha*****@gmail.c om wrote:
I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one


Efficient for what?

Efficient in disk-space used ("least source code")?

Efficient in RAM used ("smallest objects and compiled code")?

Efficient in execution time ("fastest")?

Efficient in program time ("quickest to write and debug")?

If you use regular expressions, does the time taken in loading the module
count, or can we assume you have already loaded it?

It will also help if you specify your problem a little better. Are you
replacing one word, and then you are done? Or at you repeating hundreds of
millions of times? What is the context of the problem?

Most importantly, have you actually tested your code to see if it is
efficient enough, or are you just wasting your -- and our -- time with
premature optimization?

def replace_word(so urce, newword):
"""Replace the first word of source with newword."""
return newword + " " + "".join(source. split(None, 1)[1:])

import time
def test():
t = time.time()
for i in range(10000):
s = replace_word("a a to become", "/aa/")
print ((time.time() - t)/10000), "s"

py> test()
3.6199092865e-06 s
Is that fast enough for you?
--
Steven.

Oct 22 '05 #6
ha*****@gmail.c om <ha*****@gmail. com> wrote:
I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one


I doubt you'll find faster than Sed.

man sed

--
William Park <op**********@y ahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
http://freshmeat.net/projects/bashdiff/
Oct 22 '05 #7
On Thu, 20 Oct 2005 10:25:27 -0700, Micah Elliott wrote:
I thought that string concatenation was rather
expensive, so its being faster than %-formatting surprised me a bit:


Think about what string concatenation actually does:

s = "hello " + "world"

In pseudo-code, it does something like this:

- Count chars in "hello" (six chars).
- Count chars in "world" (five chars).
- Allocate eleven bytes.
- Copy six chars from "hello " and five from "world" into the newly
allocated bit of memory.

(This should not be thought of as the exact process that Python uses, but
simply illustrating the general procedure.)

Now think of what str-formatting would do:

s = "hello %s" % "world"

In pseudo-code, it might do something like this:

- Allocate a chunk of bytes, hopefully not too big or too small.
- Repeat until done:
- Copy chars from the original string into the new string,
until it hits a %s placeholder.
- Grab the next string from the args, and copy chars from
that into the new string. If the new string is too small,
reallocate memory to make it bigger, potentially moving
chunks of bytes around.

The string formatting pseudo-code is a lot more complicated and has to do
more work than just blindly copying bytes. It has to analyse the bytes it
is copying, looking for placeholders.

So string concatenation is more efficient, right? No. The thing is, a
*single* string concatenation is almost certainly more efficient than a
single string concatenation. But now look what happens when you repeat it:

s = "h" + "e" + "l" + "l" + "o" + " " + "w" + "o" + "r" + "l" + "d"

This ends up doing something like this:

- Allocate two bytes, copying "h" and "e" into them.
- Allocate three bytes, copying "he" and "l" into them.
- Allocate four bytes, copying "hel" and "l" into them.
....
- Allocate eleven bytes, copying "hello worl" and "d" into them.

The problem is that string concatenation doesn't scale efficiently. String
formatting, on the other hand, does more work to get started, but scales
better.

See, for example, this test code:

py> def tester(n):
.... s1 = ""
.... s2 = "%s" * n
.... bytes = tuple([chr(i % 256) for i in range(n)])
.... t1 = time.time()
.... for i in range(n):
.... s1 = s1 + chr(i % 256)
.... t1 = time.time() - t1
.... t2 = time.time()
.... s2 = s2 % bytes
.... t2 = time.time() - t2
.... assert s1 == s2
.... print t1, t2
....
py> x = 100000
py> tester(x)
3.24212408066 0.01252317428
py> tester(x)
2.58376598358 0.01238489151
py> tester(x)
2.76262307167 0.01474809646

The string formatting is two orders of magnitude faster than the
concatenation. The speed difference becomes even more obvious when you
increase the number of strings being concatenated:

py> tester(x*10)
2888.56399703 0.13130998611

Almost fifty minutes, versus less than a quarter of a second.
--
Steven.

Oct 22 '05 #8
On Sat, 22 Oct 2005 21:05:43 +1000, Steven D'Aprano wrote:
The thing is, a
*single* string concatenation is almost certainly more efficient than a
single string concatenation.


Dagnabit, I meant a single string concatenation is more efficient than a
single string replacement using %.
--
Steven.

Oct 22 '05 #9
On 2005-10-22, William Park wrote:
ha*****@gmail.c om <ha*****@gmail. com> wrote:
I am looking for the best and efficient way to replace the first word
in a str, like this:
"aa to become" -> "/aa/ to become"
I know I can use spilt and than join them
but I can also use regular expressions
and I sure there is a lot ways, but I need realy efficient one


I doubt you'll find faster than Sed.


On the contrary; to change a string, almost anything will be faster
than sed (except another external program).

If you are in a POSIX shell, parameter expansion will be a lot
faster.

In a python program, one of the solutions already posted will be
much faster.

--
Chris F.A. Johnson <http://cfaj.freeshell. org>
=============== =============== =============== =============== ======
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
<http://www.torfree.net/~chris/books/cfaj/ssr.html>
Oct 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2416
by: MDW | last post by:
Mystring = Left(Mystring,Len(Mystring) - 1) Mystring = Mid(Mystring,2) That should do it. >-----Original Message----- >How can I replace first as well as last "," in a string? > >Mystring = ",3,2,5,6,1,65,22," >
13
11021
by: M | last post by:
Hi, I've searched through the previous posts and there seems to be a few examples of search and replacing all occurrances of a string with another string. I would have thought that the code below would work... string gsub(const string & sData, const string & sFrom,
1
1757
by: galsaba | last post by:
How can I replace a word in a field in all records? Let's say that I have the record "address". and the adress are: 37-08 east linwood st 121 east smith road 22 ave west apple blvd 202 galsaba east avenue etc. I want to replace the word "east" in the field address on all records
5
4581
by: Wasim Akram | last post by:
Hi all, String.Replace replaces all occurrances of a substring in a given string . Can anyone guide me how can I replace first occurrance of a substring in a given string. - wa
2
6222
by: shapper | last post by:
Hello, I want to remove the first word of a string. For example: MyString = "Hello World! How are you?" I need to create 2 string: MyString1 = "Hello"
3
9075
by: nickyeng | last post by:
i was wondering how to replace a word in a line. i search in google.com and thescipts.com, i hardly to find what i want. for example this line, "I like his daughter" replace his with "her".
8
1564
by: groups2 | last post by:
In this example, if officename has more than one word, the only word added to the input field is the first word. document.getElementById('office').innerHTML="Office / Company Name:<input type='text' name='org' size='30' id='org' value="+officename+" />"; What happened to the other words and How do I get it to show all the words ?
4
2408
MrPickle
by: MrPickle | last post by:
I am tokenizing a line using a stringstream and a vector but the stringstream seems to be repeating the first word, here's my code: std::stringstream ss; std::vector<std::string> LineVec; std::string Line, Word; while(std::getline(File, Line)) { if(Line.empty()) { continue; } ss.str(Line); ss.seekg(std::ios::beg);
2
1847
by: whodgson | last post by:
The following code accepts a string from the user and swaps the first and last letters in each word. It prints out the original string incorrectly by dropping off the first letter of the first word. I would like to establish what error in the code is causing the first word to be mangled. #include<iostream> #include<cstring> #include<cstdlib> using namespace std; int main() { cout<<"Transposing letters in a string \n"; cout<<"Type a...
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9307
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.