Austin
Austin

Reputation: 7319

Convert list of strings to proper directory names with backslash

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

Answers (2)

Taku
Taku

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

Martijn Pieters
Martijn Pieters

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

Related Questions