+ 1
replace dosent work python
s = " a a a a " s = s.replace(" a ", " ") print (s) Edit: but when i write s = s.replace("a", " ") It works fine but also replaces a between words like *package*, so i get *pckge* I want to replace all a's with space, so i get empty string as an output which has only spaces but i get " a a " as output Please help fast And if possible please show me same with python re module, as i have done same with re module but get same result Re module code: s = re.sub(" a ", " ", s)
12 RĂ©ponses
+ 6
Kairav Bhatia
replace with a pattern of " a ", replaced with "" and a given string of " a a a a " should result in "aa ". This is because the first " a " in the string is replaced then the second a no longer has a space before it and doesn't match. Then the 3rd a matches and is replaced, but now the 4th doesn't have a space before it, so it doesn't match and you're left with the final string of "aa ".
The progression is as follows:
" a a a a "
"a a a "
"aa "
Hope this helps your understanding of what your issue was.
+ 2
maybe you need to remove the space in the forst argument of replace()?
s = s.replace("a", " ")
this won't be an empty string as it will result with " "
if you want a to remove all a and spaces you either need to use the replace function twice or use a regex that looks like this: "[a ]"
I hope this helps :)
+ 1
import rel
s='a a a a'
s= s,replace('a',")
print([s])
s= s.replace('a',")
print(s)
This should do it, [a] won't work in python.
0
SoloProg i have already searched this site but does not help
0
<â
Shaurya Chauhanâ
>(Inspiration will draw you)
Thanks but in replace line i want
" a " not "a" and also in string i want spaces not commas
0
Apollo-Roboto thanks but i need spaces in first argument of replace
0
Apollo-Roboto thanks a lot your regex command worked for me, and can you give me a little explanation about it that why "[a ]" did work and not " a "
0
I will try sorry for deleting the comment
Because I saw the question then I realized that I had given wrong answer
I will try
0
It worked but not well, it also removes a between words and i only want to removes a which contains spaces on both sides
Apollo-Roboto
0
See this now
Kairav Bhatia
is it right
https://code.sololearn.com/cgGaFkMv8dj3/?ref=app
0
ChaoticDawg but i replace ' a ' with ' ' so it should not be a problem
0
import re
s = ' a a a a'
s = s.replace(' a', '')
print([s])
s = "package"
s = s.replace(' a', '')
print(s)
s = re.sub(" +a",'', s)
print(s)
This should do it. [ a] won't work.