0

I have Python 2.7 code that operates on a list of files. In part of the code I strip away the directory information. Today I was surprised to find that code didn't work correctly, when the file names begin with "s". This sample code demonstrates the problem:

import os

TEST_RESULTS_DIR = ".." + os.sep + "Test Results"

filename = TEST_RESULTS_DIR + os.sep + "p_file.txt"
stripped_filename = filename.lstrip(TEST_RESULTS_DIR + os.sep)
print ("%s : %s") % (filename, stripped_filename)

filename = TEST_RESULTS_DIR + os.sep + "s_file.txt"
stripped_filename = filename.lstrip(TEST_RESULTS_DIR + os.sep)
print ("%s : %s") % (filename, stripped_filename)

When I run this code, I get this:

..\Test Results\p_file.txt : p_file.txt

..\Test Results\s_file.txt : _file.txt

Does anyone understand why?

Community
  • 1
  • 1
BigBobby
  • 423
  • 1
  • 3
  • 17

1 Answers1

1

Lstrip doesn't replace a string at the beginning of another string, it strips all characters that match the characters in the string argument from the string it is called on.

For example:

"aaabbbc".lstrip("ba") = "c"

Your directory has an s in it, so it get's striped, you would see the same result if the file started with a u or an e.

Nick Bailey
  • 3,078
  • 2
  • 11
  • 13