文字列を URL フレンドリーなスラッグに変換する

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

Web 開発では、ランダムな文字ではなく読みやすい単語を含む URL が一般的です。これらの読みやすい単語はスラッグと呼ばれます。スラッグは、URL をユーザーにとって使いやすく覚えやすくするために使用されます。このチャレンジでは、文字列を URL フレンドリーなスラッグに変換する関数を作成します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/AdvancedTopicsGroup(["Advanced Topics"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/AdvancedTopicsGroup -.-> python/regular_expressions("Regular Expressions") subgraph Lab Skills python/comments -.-> lab-13715{{"文字列を URL フレンドリーなスラッグに変換する"}} python/lists -.-> lab-13715{{"文字列を URL フレンドリーなスラッグに変換する"}} python/tuples -.-> lab-13715{{"文字列を URL フレンドリーなスラッグに変換する"}} python/function_definition -.-> lab-13715{{"文字列を URL フレンドリーなスラッグに変換する"}} python/importing_modules -.-> lab-13715{{"文字列を URL フレンドリーなスラッグに変換する"}} python/standard_libraries -.-> lab-13715{{"文字列を URL フレンドリーなスラッグに変換する"}} python/regular_expressions -.-> lab-13715{{"文字列を URL フレンドリーなスラッグに変換する"}} end

文字列からスラッグへ

文字列 s を引数として受け取り、スラッグを返す関数 slugify(s) を作成します。この関数は次の操作を行う必要があります。

  1. 文字列を小文字に変換し、先頭または末尾の空白を削除します。
  2. すべての特殊文字(つまり、文字、数字、空白、ハイフン、またはアンダースコアでない任意の文字)を空文字列に置き換えます。
  3. すべての空白、ハイフン、およびアンダースコアを単一のハイフンに置き換えます。
  4. 先頭または末尾のハイフンを削除します。
import re

def slugify(s):
  s = s.lower().strip()
  s = re.sub(r'[^\w\s-]', '', s)
  s = re.sub(r'[\s_-]+', '-', s)
  s = re.sub(r'^-+|-+$', '', s)
  return s
slugify('Hello World!') ## 'hello-world'

まとめ

このチャレンジでは、文字列を URL に対してフレンドリーなスラッグに変換する関数を作成する方法を学びました。特殊文字を削除し、空白、ハイフン、アンダースコアを単一のハイフンに置き換えるために、文字列メソッドと正規表現を使用しました。このチャレンジを完了することで、Python で文字列を操作する方法をより深く理解することができました。