change a string conditional
Rich Harkins
rharkins at thinkronize.com
Thu May 9 13:21:48 EDT 2002
On Thursday 09 May 2002 01:02 pm, obantec support wrote:
> Hi
>
> I need to a piece of python code that will take a string which may or may
> not begin with www and change it to lists.
>
> eg. www.domain.com becomes lists.domain.com
> but if domain1.com (no www) the it still becomes lists.domain1.com
>
> an example of a pattern match will be enough.(I do a bit of perl but never
> done any python)
>
> mark
Assuming that you always want to preserve the last two segments of the
hostname (the y and z in x.y.z and w.x.y.z) you don't need pattern matches at
all...
def translate(host,prefix):
"""
Removes everything from host before the main domain name and places
prefix there instead.
"""
# One line version: return '.'.join(['lists']+host.split('.')[-2:])
parts=host.split('.')[-2:] # Break into parts
parts=[prefix]+parts # Stick prefix in front of parts.
return '.'.join(parts) # Join it all together with '.''s in between.
print translate('www.domain.com','lists')
print translate('domain.com','lists')
print translate('a.weird.subdomain.domain.com','lists')
(The output is):
lists.domain.com
lists.domain.com
lists.domain.com
I think that's what you were asking for - or did I miss it?
Rich
More information about the Python-list
mailing list