Reputation: 3452
Can someone please post a python snippet to create a link based on the title, like in stackoverflow (or wordpress)...
e.g.
title : Global across "Modules" ?
corresponding link : http://example.com/8277516/globals-across-modules
I do not need any chars other than alphabets or numbers or '-'. Also i don't need the starting or ending character of the output string to be '-'
Upvotes: 1
Views: 189
Reputation: 55263
You probably don't want to reinvent the wheel, so, you might want to use Django's slugify filter. Of course, you don't need to use Django to use it, and you could try and have a look at the source code and just get what you want so you don't have to have the whole Django packages installed to make this work.
Here's what you'll get:
>>> from django.template.defaultfilters import slugify
>>> slugify("""Global across "Modules" ?""")
u'global-across-modules'
>>>
Note that slugs are meant to be used in URLs in Django, so they're URL safe.
Upvotes: 1
Reputation: 336428
How about this:
>>> import re
>>> s = 'Global across "Modules" ?'
>>> '-'.join(item.lower() for item in re.findall(r'\w+', s))
'global-across-modules'
This works on Python 2; there it will keep only ASCII alphanumeric characters. Under Python 3, it will also keep Unicode alphanumerics, which might not be what you want.
Upvotes: 2
Reputation: 7344
I'd suggest a dictionary with input and output and a fallback.
>>> s = "Tür auf"
>>> repl = {'ü' : 'u', ' ': '-'}
>>> f = lambda i: repl.get(i, '-')
>>> "".join(map(f, s)).lower()
'tur-auf'
edit
wrong ;) because T and r are not in the replacements dict. But I hope you get the idea. You can get a list with all letters like that:
>>> [chr(i) for i in range(97, 123)]
Now you need a function that checks if the letter or it's lowercase is in the list, if yes, use it, if not, replace it with the dict values.
Upvotes: 0