Login

Digg Style URL String Parser

Author:
addicted
Posted:
March 26, 2007
Language:
Python
Version:
.96
Score:
-2 (after 2 ratings)

Does a digg url effect to a string, can be useful for using an item's title in the url,

from this:

.hi's., is (a) $ [test], will it "work"/ \

to this:

his_is_a_test_will_it_work

I understand this isn't a very well made script, I am not very good at string manipulation. But I would be happy if someone would recode it in a faster, more managable way. I recomend saving the rendering.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def urlsafestring(string):
	from string import strip, rstrip, lstrip, replace
	string = str(string)
	badchars = [".",",","+","=","%","#","!","@","$","^","*","(",")","\\","/","\"","[","]","{","}","|","'","?"]
	for b in badchars:
		string = replace(string, b, "")
	string = rstrip(string)
	string = lstrip(string)
	string = replace(string, "-", "_")
	string = replace(string, " ", "_")
	string = replace(string, "__", "_")
	return string

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

derivin (on March 26, 2007):

this might be better:

import re
match_non_alnum = re.compile("[^a-zA-Z0-9]+")

def dig_url_encode(string):
    return match_non_alnum.sub(' ', string).strip().replace(' ', '_')

Example:

>>> dig_url_encode('.hi\'s., is (a) $ [test], will it "work"/ \\')
'hi_s_is_a_test_will_it_work'
>>>

#

robbie (on March 30, 2007):

Isn't this essentially the same as Django's slugify filter?

#

Please login first before commenting.