how to remove spaces in between of a string in python?

Viewed 51

Suppose I have a string : ' Swarnendu Pal is a good boy ' Here I want to remove all the spaces in between the strings, that means the leading and the last spaces should be remain same but all other spaces should be removed. My final expected output will be : ' SwarnenduPalisagoodboy '

2 Answers

Try this... doesn't matter #spaces you have in the start/end... the code will retain them... & remove in between strings...

s = " Swarnendu Pal is a good boy "
start_space, end_space = 0,0
for i in s:
    if i == " ":
        start_space += 1
    else:
        break
for i in s[::-1]:
    if i == " ":
        end_space += 1
    else:
        break
result = " " * start_space + s.replace(" ","") + " " * end_space
print(result)

# " SwarnenduPalisagoodboy " #### output

Hope this helps...

An attempt at regular expression, which will remove consecutive white space characters with non white space characters outside both ends (I'm not very good at using it yet, and there may be a better solution):

>>> import re
>>> re.sub(r'(?<=[^ ]) +(?=[^ ])', '', ' Swarnendu Pal is a good boy ')
' SwarnenduPalisagoodboy '
Related