I have the string "How are you"
. This string should become "How-are-you"
.
It's possible with regex? How?
Asked
Active
Viewed 1.9k times
0
-
4Have you tried looking at the simple replace space with '-'. – aweis Aug 11 '13 at 17:01
-
2What do you want `"Two spaces"` to become? `"Two--spaces"` or `"Two-spaces"`? What about `"space and\ttab"`? `"space-and-tab"` or `"space-and\ttab"`? – DSM Aug 11 '13 at 17:07
5 Answers
7
Another option is replace
$ python -m timeit 'a="How are you"; a.replace(" ", "-")'
1000000 loops, best of 3: 0.335 usec per loop
$ python -m timeit 'a="How are you"; "-".join(a.split())'
1000000 loops, best of 3: 0.589 usec per loop

Jared
- 25,627
- 7
- 56
- 61
-
Yeah but aweis beat you to that answer by 13 minutes as well as Bryan by 2 minutes. split() has some advantages over replace(), e.g. if there might be more than one space or even tabs between the words. – 7stud Aug 11 '13 at 17:28
5
Just use pythons built in replace method:
strs = "How are you"
new_str = strs.replace(" ","-")
print new_str // "How-are-you"

Bryan
- 1,938
- 13
- 12
3
Why use a regex?
x = "How are you"
print "-".join(x.split())
--output:--
How-are-you

7stud
- 46,922
- 14
- 101
- 127
3
Depending on your precise needs, there is many variation on that theme using regular expressions:
# To replace *the* space character only
>>> re.sub(' ', '-', "How are you");
# To replace any "blank" character (space, tab, ...):
>>> re.sub('\s', '-', "How are you");
# To replace any sequence of 1 or more "blank" character (space, tab, ...) by one hyphen:
>>> re.sub('\s+', '-', "How are you");
# To replace any sequence of 1 or more "space" by one hyphen:
>>> re.sub(' +', '-', "How are you");
Please note for "simple" substitution replace is probably more appropriate than using regular expression (those are really powerful, but requires a compilation phase before processing that could be expensive. Not sure this would really impact your program for such a simple case though... ;). Finally for the one special case or replacing sequences of spaces, nothing could probably beat x.join(str.split())
...

Sylvain Leroux
- 50,096
- 7
- 103
- 125
2
As you asked, using regex:
>>> import re
>>> s = "How are you"
>>> print re.sub('\s', '-', s)
How-are-you

alecxe
- 462,703
- 120
- 1,088
- 1,195