I want to replace whitespace with underscore in a string to create nice URLs. So that for example:
\"This should be connected\" becomes \"This_should_be_conn
Surprisingly this library not mentioned yet
python package named python-slugify, which does a pretty good job of slugifying:
pip install python-slugify
Works like this:
from slugify import slugify
txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")
txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")
txt = 'Компьютер'
r = slugify(txt)
self.assertEquals(r, "kompiuter")
txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")
OP is using python, but in javascript (something to be careful of since the syntaxes are similar.
// only replaces the first instance of ' ' with '_'
"one two three".replace(' ', '_');
=> "one_two three"
// replaces all instances of ' ' with '_'
"one two three".replace(/\s/g, '_');
=> "one_two_three"
This takes into account blank characters other than space and I think it's faster than using re
module:
url = "_".join( title.split() )
mystring.replace (" ", "_")
if you assign this value to any variable, it will work
s = mystring.replace (" ", "_")
by default mystring wont have this
You can try this instead:
mystring.replace(r' ','-')
use string's replace method:
"this should be connected".replace(" ", "_")
"this_should_be_disconnected".replace("_", " ")