Python remove spaces and append

3.1k views Asked by At

I am currently writing a growl notification plugin for emesene messenger on OS X. It is nearly working except to when it comes to displaying a message snippet.

The message is passed to growlnotify as a variable, however growl does not accept spaces in the displayed message.

So what i need help with is a script to remove the spaces between multiple words and replace it with a \ then a space.

e.g. Original: This is a message What is needed: This\ is\ a\ message

I have looked around at similar answers but i could not work out how to append the slash.

5

There are 5 answers

0
Ignacio Vazquez-Abrams On BEST ANSWER

Instead of trying to do this with os.system(), use subprocess instead, passing the program and arguments as a list.

1
MGwynne On

Just use the replace method of the string class:

message_string = "This is a message"
print message_string.replace(" ", "\ ")

returns:

$ python test.py
This\ is\ a\ message

See Python string.replace documentation.

0
cji On
message = "This is a message"
print message.replace( " ", "\ " )
0
Michael J. Barber On

You can do this using the replace method of strings.

2
trutheality On

Everyone's using replace, so here's the other solution:

print '\ '.join(message.split(' '))