change a string conditional

Martin v. Loewis martin at v.loewis.de
Thu May 9 13:48:17 EDT 2002


"obantec support" <spam at nomail.net> writes:

> 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)

The simplest approach is the startswith method:

def inject_lists(host):
    if host.startswith("www."):
      host = host[4:]
    return "lists."+host

print inject_lists("www.domain.com")
print inject_lists("domain.com")

The other two items needed are "string slicing": host[4:] returns the
tail string of host, starting with the fourth character, and string
concatenation (which is spelled as "+").

HTH,
Martin




More information about the Python-list mailing list