[英]python replace all special characters and spaces with single '-'
[英]Remove special characters and replace spaces with “-”
我正在嘗試創建一個可以出現在 URL 中的目錄。 我想確保它不包含任何特殊字符並用連字符替換任何空格。
from os.path import join as osjoin
def image_dir(self, filename):
categorydir = ''.join(e for e in str(self.title.lower()) if e.isalnum())
return "category/" + osjoin(categorydir, filename)
它正在刪除特殊字符,但是我想使用.replace(" ", "-")
用連字符替換空格
最好的方法可能是使用slugify
function 它將任何字符串作為輸入並返回與 URL 兼容的字符串,你的不是 URL 但它會成功,例如:
>>> from django.utils.text import slugify
>>> slugify(' Joel is a slug ')
'joel-is-a-slug'
為什么不使用報價function?
import urllib.parse
urlllib.parse.quote(filename.replace(" ", "-"), safe="")
您可以創建此函數並調用remove_special_chars(s)來執行此操作:
def __is_ascii__(c):
return (ord(c) < 128)
def remove_special_chars(s):
output = ''
for c in s:
if (c.isalpha() and __is_ascii__(c)) or c == ' ':
output = output + c
else:
if c in string.punctuation:
output = output + ' '
output = re.sub(' +', ' ', output)
output = output.replace(' ', '-')
return output
它將刪除每個非 ASCII 字符和string.punctuation中的每個元素
編輯:這個 function 將用'-'替換string.punctuation中的每個元素,如果你想你可以在 else 語句中用''替換''來合並標點元素之前和之后的兩個部分字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.