2

I have this code to change directory information in python. I'd like to change '/a/b/c' into '/x/b/c'.

import os x = "/a/b/c" y = x.split(os.sep) y[1] = 'x' os.sep.join(y) 

Now I just want to know if python can make it one-liner. I can't simply use os.sep.join(x.split(os.sep)[1] = 'x') as it causes an syntax error. What might be other options in python?

1
  • 2
    Why do you have to do it in one line? Commented Dec 28, 2012 at 15:00

3 Answers 3

3
os.sep.join('x' if idx == 1 else element for idx, element in enumerate(x.split(os.sep))) 

result:

'/x/b/c' 

Explanation: enumerate pairs each element of x.split(os.sep) with its index. 'x' if idx == 1 else element replaces the element with 'x' if it is the 1th element, and leaves it intact otherwise.

Sign up to request clarification or add additional context in comments.

Comments

2

This is likely rather inefficient:

y = os.sep.join([x.split(os.sep)[0]] + ['x'] + x.split(os.sep)[2:]) 

3 Comments

If you don't want to call split twice, you could use a lambda function, like this: (lambda elements: os.sep.join([elements[0]] + ['x'] + elements[2:]))(x.split(os.sep))
@Kevin That's pretty clever! I like it.
Yes, it's very useful for one-liners, since assignment is impossible. Whenever you ask yourself, "how do I calculate a value once and use it multiple times later?", consider using lambda.
0

This seems to work too:

y = os.sep + 'x'+ x[2:] 

1 Comment

It does for the example case, but would fail in a number of situations, such as x not starting with os.sep, the top-level directory contained more than one character, if os.sep itself wasn't a single character... this is why using os.path functions is so important.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.