This doesn't work as sep requires several parameters in print to have an effect.
You have many ways.
split and unpacking:
s = 'Hi I am Mike'
print(*s.split(), sep="...")
split and str.join:
s = 'Hi I am Mike'
print('...'.join(s.split()))
str.replace:
s = 'Hi I am Mike'
print(s.replace(' ', '...'))
Output: Hi...I...am...Mike
python - How to replace whitespaces with underscore? - Stack Overflow
python - Replace spaces in string - Code Review Stack Exchange
Replace single character in string with space
substitution - Substitute multiple whitespace with single whitespace in Python - Stack Overflow
This doesn't work as sep requires several parameters in print to have an effect.
You have many ways.
split and unpacking:
s = 'Hi I am Mike'
print(*s.split(), sep="...")
split and str.join:
s = 'Hi I am Mike'
print('...'.join(s.split()))
str.replace:
s = 'Hi I am Mike'
print(s.replace(' ', '...'))
Output: Hi...I...am...Mike
The sep only works if you provide multiple strings. Like this:
strings = ["Hi", "I", "am", "Mike"]
print(strings[0],strings[1],strings[2],strings[3], sep="...")
So first split your input on spaces, then combine those with the sep parameter.
my_input = input()
my_input.split()
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.
A simple possibility (if you'd rather avoid REs) is
' '.join(mystring.split())
The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).
A regular expression can be used to offer more control over the whitespace characters that are combined.
To match unicode whitespace:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"\s+")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()
To match ASCII whitespace only:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)
Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.
Reference:
About \s:
For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.
About re.ASCII:
Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).
strip() will remote any leading and trailing whitespaces.
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))
I would recommend using urllib.parse module and its quote() function.
https://docs.python.org/3.6/library/urllib.parse.html#urllib.parse.quote
Example for Python3:
from urllib.parse import quote
text_encoded = quote(t.text)
Note: using quote_plus() won't work in your case as this function replaces spaces by plus char.
Use the String.replace() method as described here: http://www.tutorialspoint.com/python/string_replace.htm
So for t.text, it would be t.text.replace(" ", "%20")