0

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"
OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
  • 1
    Sounds great. Tried anything yet? – OneCricketeer Nov 10 '16 at 16:13
  • This maybe `'-'.join(s.split())`, but your symbol removal requirement makes it vague – Moses Koledoye Nov 10 '16 at 16:13
  • 1
    Look at [String slugification in Python](http://stackoverflow.com/questions/5574042/string-slugification-in-python) – vishes_shell Nov 10 '16 at 16:15
  • Its good that you need something but can you tell us what have you done/tried on doing it? Don't just come here asking us to do your work. We are here to help you solve problems not to write all the code for you. –  Nov 10 '16 at 16:15
  • My first idea was make the string into a list by separated by spaces. Then It was removing the special characters in each element of the list. Finally joining the list into a string again with "-" in between elements – James B Lee Nov 10 '16 at 16:25

4 Answers4

0
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.

Alex Hall
  • 31,431
  • 4
  • 39
  • 71
0

How about this (the drawback is unable to remain the hyphen -),

import string

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

table = string.maketrans(" ", "-") 
new_s = s.translate(table, string.punctuation)  

print(new_s)
# the-cows-milk-is-aokay
SparkAndShine
  • 14,337
  • 17
  • 76
  • 119
0
>>> string = "the cow's milk is a-okay!"
>>> string
"the cow's milk is a-okay!"
>>> string = string.replace(' ','-')
>>> for char in string:
...     if char in "?.!:;/'":
...             string = string.replace(char,'')
...
>>> string
'the-cows-milk-is-a-okay'
Simeon Aleksov
  • 941
  • 1
  • 9
  • 19
0

A simple generator expression could be used to accomplish this:

>>> s = "the cow's milk is a-okay!"
>>> ''.join(('-' if el == " " else el if el not in "?.!:;/'" else "" for el in s))
'the-cows-milk-is-a-okay'
>>> 
Christian Dean
  • 19,561
  • 6
  • 42
  • 71