String slugification in Python

前端 未结 10 1090
粉色の甜心
粉色の甜心 2020-11-30 23:10

I am in search of the best way to \"slugify\" string what \"slug\" is, and my current solution is based on this recipe

I have changed it a little bit to:

<         


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 00:07

    def slugify(value):
        """
        Converts to lowercase, removes non-word characters (alphanumerics and
        underscores) and converts spaces to hyphens. Also strips leading and
        trailing whitespace.
        """
        value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
        value = re.sub('[^\w\s-]', '', value).strip().lower()
        return mark_safe(re.sub('[-\s]+', '-', value))
    slugify = allow_lazy(slugify, six.text_type)
    

    This is the slugify function present in django.utils.text This should suffice your requirement.

提交回复
热议问题