You don't need regular expressions. Python has a built-in string method that does what you need:
mystring.replace(" ", "_")
Answer from rogeriopvl on Stack Overflowpython - How to replace whitespaces with underscore? - Stack Overflow
python - Replace spaces in string - Code Review Stack Exchange
Python 3 - can't delete a space in a string using replace - Stack Overflow
methods to remove spaces from text
You don't need regular expressions. Python has a built-in string method that does what you need:
mystring.replace(" ", "_")
Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc.
Also note that the general consensus among SEO experts is that dashes are preferred to underscores in URLs.
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '-', s)
return s
# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))
If you want to avoid replace, a faster method would just split and join. This is faster simply because .split and .join are fast:
"20%".join(string.split(" "))
For a more thorough review, I'll point out that your functions aren't equivalent. The first strips whitespace and the second doesn't. One of them must be wrong!
In the second case:
def replace_token_inplace(s, token=" "):
for index, char in enumerate(s):
if ord(char) == ord(token):
s[index] = '20%'
return s
you are doing several non-idiomatic things. For one, you are mutating and returning a list. It's better to just not return it if you mutate:
def replace_token_inplace(s, token=" "):
for index, char in enumerate(s):
if ord(char) == ord(token):
s[index] = '20%'
Secondly, it'll probably be faster to do a copying transform:
def replace_token_inplace(s, token=" "):
for char in s:
if ord(char) == ord(token):
yield '20%'
else:
yield char
which can also be written
def replace_token_inplace(s, token=" "):
for char in s:
yield '20%' if ord(char) == ord(token) else char
or even
def replace_token_inplace(s, token=" "):
return ('20%' if ord(char) == ord(token) else char for char in s)
If you want to return a list, use square brackets instead of round ones.
Why not use the Python standard function:
"Foo Bar ".replace("20%"," ")
It's built-in, so experts have optimised this as much as possible.
Hi everyone, I recently took the Fullstack Python Developer course and am now taking my first steps on this path.
Can you tell me what other methods of removing spaces from text you know and in which case, each of them is better to use?
So far I know 4 of them:
-
replace method -> text_wo_spaces = text.replace(" ","")
-
join and split methods -> text_wo_spaces = ' '.join(text.split())
-
list generator + join -> text_wo_spaces = ' '.join([char for char in text if char != ' '])
-
filter + join methods -> text_wo_spaces = ' '.join(filter(lambda char : != ' ', text))
Are you compelled to use regex? This task can easily ne accomplished by using str.translate and string.punctuation as the deletechars
>>> from string import punctuation
>>> a="what is. your. name? It's good"
>>> a.translate(None, punctuation)
'what is your name Its good'
If you are compelled to use regex, another option for you would be
>>> from string import punctuation
>>> r = re.compile(r'[{}]+'.format(re.escape(punctuation)))
>>> r.sub('', a)
'what is your name Its good'
But, I would still suggest you to reconsider the design. Using Regex for this task is an overkill.
To match any word character and a single quoted comma ' if there is any.:
import re
string = "Many cook's were involved and many cooked pre-season food"
punctaution = re.findall(r"\w+([\-_.!~*'()])\w+",string)
for i in punctaution:
string = re.sub(i,'',string)
print string
Output:
Many cooks were involved and many cooked preseason food