- Removes white spaces from your string only when its outside the delimiter you define!
I was looking for some ready-made python function which I was very sure about finding it easily.
So, I started googling a function which will only remove white-spaces from the string when the set of characters within the string are not around double quotes. When I didn’t find it I thought if I had to write this code, I might as well make it generic and also pass the delimiter as input to have the option to choose what I wish to define as a block that wouldn’t apply in the string. It’s really not a big deal, very very simple and I hope this post helps you save some time instead of spending time making the function code work!
def selective_ws_remover(your_str , your_delimiter ):
x= []
result= ''
x= your_str.split(your_delimiter)
for i in range(len(x)):
if i % 2 == 0: #is odd
x[i] = ' '.join(x[i].split())
x[len(x)-1]= ' '.join(x[len(x)-1].split())
for i in range(len(x)):
if i < len(x)-1 :
result= result + x[i] + your_delimiter
else:
result= result + x[i]
result= result.rstrip()
print result
Example:
>>>y= 'name\t\n:"John Smith \t->(Jr.) " \n\t\t\tTitle:\n\t"IT Professional \t->(Finance)"'>>> selective_ws_remover(y,'"')
name :"John Smith ->(Jr.) "Title:"IT Professional ->(Finance)"
White spaces removed only from characters not in double quotes.
-Ritu Mishra, Full360





