Python remove spaces and append

痞子三分冷 提交于 2019-12-11 18:18:24

问题


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.


回答1:


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




回答2:


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.




回答3:


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



回答4:


You can do this using the replace method of strings.




回答5:


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

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


来源:https://stackoverflow.com/questions/6289915/python-remove-spaces-and-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!