best way to replace first word in string?

Larry Bates larry.bates at websafe.com
Thu Oct 20 12:16:44 EDT 2005


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.split(' ',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


hagai26 at 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
> 



More information about the Python-list mailing list