Python Forum
remove spaces with exceptions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: remove spaces with exceptions (/thread-27195.html)



remove spaces with exceptions - catosp - May-29-2020

Hello!

I have the following problem:

This is the string: asdas asdd sd a2123 3234 "test asd" asda

Is possible to remove all spaces except the spaces between "" ?

Thank you!


RE: remove spaces with exceptions - buran - May-29-2020

where does this string come from - is it a file
if it comes from a file, you can use csv module, if it's just a string - you can use io.StringIO and then csv module
spam = 'asdas asdd sd a2123 3234 "test asd" asda'

import io
import csv
eggs = io.StringIO(spam)

rdr = csv.reader(eggs, delimiter=' ')
for line in rdr:
    print(line)
Output:
['asdas', 'asdd', 'sd', 'a2123', '3234', 'test asd', 'asda']
you can further process the list to get desired output


RE: remove spaces with exceptions - catosp - May-29-2020

Ok, managed to write some piece of code to do the job:
word = "asdas asdd sd a2123 3234 \"test asd sdd 12 3231  123\" asda"

quo = False
wordT = ""

for letter in word:
        
    if letter == "\"" and quo == False:
        quo = True
        wordT += letter
        continue
        
    if quo == False:
        wordT += letter
    
    if quo == True:
        if letter == " ":
            wordT += "_"
        else:
            wordT += letter
    
    if letter == "\"" and quo == True:
        quo = False

print(wordT.replace(" ","").replace("_"," "))
Output:
asdasasddsda21233234"test asd sdd 12 3231 123"asda
But the solution is not very elegant.


RE: remove spaces with exceptions - pyzyx3qwerty - May-29-2020

You could use @buran's solution and just fix the print statement to
print(''.join(line))



RE: remove spaces with exceptions - catosp - May-29-2020

@buran and @pyzyx3qwerty
Thank you all !
I will use the @buran solution.