Add space between double quotes
p = '"fred", "bert", "blah"'
p.replace('\"'," ")
' fred , bert , blah '
Answer from fahad on Stack Overflowpython - How to replace every space within a text - Stack Overflow
python - Replacing a letter with a space - Stack Overflow
python - Replace spaces in string - Code Review Stack Exchange
python - Replacing characters in string by whitespace except digits - 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()
To replace all occurrences of t and T with a space in the string input, use the following:
input = input.replace('t', ' ').replace('T', ' ')
Or with regular expressions:
import re
input = re.sub('[tT]', ' ', input)
Why not simply use the replace function?
s = 'The book on the table thttg it Tops! Truely'
s.replace('t', ' ').replace('T', ' ')
yields:
' he book on he able h g i ops! ruely'
maybe not as nice as using a regular expression, but functional.
However, this seems substantially faster than the regular expression approach (thanks to @JoranBeasley motivating the benchmarking):
timeit -n 100000 re.sub('[tT]', ' ', s)
100000 loops, best of 3: 3.76 us per loop
timeit -n 100000 s.replace('t', ' ').replace('T', ' ')
100000 loops, best of 3: 546 ns per loop
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.
import re
s1=re.sub(r"[^0-9 ]"," ",s)
You can use re here.
To prevent . of floating numbers use
(?!(?<=\d)\.(?=\d))[^0-9 ]
Instead of using a regular expression, you could simply use a list comprehension:
>>> s='das dad 67 8 - 11 2928 313'
>>> ''.join([c if c.isdigit() else ' ' for c in s])
' 67 8 11 2928 313'
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!"))
The piece of code:
a = ''.join([ch for ch in text if ch not in exclude])
is equivalent to
string_without_punctuation = ''
exclude = set(string.punctuation) # =set('!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~')
for character in text:
if character not in exclude:
string_without_punctuation += character
You could simply do this to replace the punctuation with spaces:
string_without_punctuation = ''
exclude = set(string.punctuation) # =set('!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~')
for character in text:
if character not in exclude:
string_without_punctuation += character
else:
string_without_punctuation += ' '
I'd recommend using str.translate instead of manually rebuilding the string. Make a lookup table mapping characters to the strings you want to replace them with.
trans = str.maketrans(dict.fromkeys(string.punctuation, ' '))
"hello_there?my_friend!".translate(trans)
# 'hello there my friend '
You may use a (?<=\d) to require a digit before the whitespace:
release = re.sub(r"(?<=\d)\s+", ",", release)
See the regex demo
Details
(?<=\d)- a positive lookbehind that requires a digit to appear immediately to the left of the current location\s+- 1 or more whitespace chars.
You can try with backreferences:
>>> re.sub(r"(\d)\s+", r"\1,", '8.1.7 Sep 2000 Dec 2004 Dec 2006 Indefinite')
'8.1.7,Sep 2000,Dec 2004,Dec 2006,Indefinite'
So the code is:
release = re.sub(r"(\d)\s+", "\1,", release)
Explaination:
(\d)match a digit and put it in a first matching group\s+match whitespaces- in substitution:
\1references to the digit you found and puts it back (without spaces)