Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string, removing special characters and replacing

I need to convert my string so that it is made into a special format

ex:

string = "the cow's milk is a-okay!"

converted string = "the-cows-milk-is-a-okay"
like image 626
James B Lee Avatar asked Feb 20 '26 16:02

James B Lee


1 Answers

import re

s = "the cow's milk is a-okay!"
s = re.sub(r'[^a-zA-Z\s-]+', '', s)  # remove anything that isn't a letter, space, or hyphen
s = re.sub(r'\s+', '-', s)  # replace all spaces with hyphens
print(s)   # the-cows-milk-is-a-okay

Here a 'space' is any whitespace character including tabs and newlines. To change this, replace \s with the actual space character .

Runs of multiple spaces will be replaced by a single hyphen. To change this, remove the + in the second call to re.sub.

like image 146
Alex Hall Avatar answered Feb 23 '26 05:02

Alex Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!