Reputation: 7319
I have a list of strings that have spaces in them. I want to change every string so that there's a backslash before the spaces so that they can be used as directory names. What's a short way to do this, possibly with list comprehension or something?
example with longer code:
directories = []
for s in schools:
words = s.split(' ')
directory = '\\ '.join(words)
directories.append(directory)
Upvotes: 4
Views: 1689
Reputation: 33714
You can use os.path.join
because it return paths that supports cross platform. This way is the preferred way of joining directory paths
import os
directories = [os.path.join(s.split(' ')) for s in schools]
Upvotes: 0
Reputation: 1121486
Use str.replace()
, which is going to be much more efficient than splitting and re-joining. If you have a list, a list comprehension can do this for every string in the list:
escaped = [s.replace(' ', r'\ ') for s in list_of_strings]
Upvotes: 2