Python Forum

Full Version: remove spaces with exceptions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
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
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.
You could use @buran's solution and just fix the print statement to
print(''.join(line))
@buran and @pyzyx3qwerty
Thank you all !
I will use the @buran solution.