[Tutor] how to use replace() from a list

Kent Johnson kent37 at tds.net
Sun Jun 17 22:28:33 CEST 2007


Norman Khine wrote:
> 
> Hi I have this class:
> 
> def title_to_name(title):
>     title = title.encode('ascii', 'replace')
>     name = title.lower().replace('/', '_').replace('?',
> '_').replace('.', '')
>     return '_'.join(name.split())
> 
> Is there a way to have just one replace and so that:
> 
> replace('/', '_').replace('?', '_').replace('.', '_')

You can use re.sub():
In [1]: title = 'www.example.com/foo?bar'
In [2]: import re
In [5]: re.sub(r'[/?.]', '_', title)
Out[5]: 'www_example_com_foo_bar'

Kent


More information about the Tutor mailing list