-2

I am copying files from one folder into another. The files contain dashes '-' and spaces ' ' . For example, test-file 123.dwg I need to replace those hyphens and spaces with underscores so it would look like this test_file_123.dwg

I've tried this and it replaces the hyphen fine but no the space. If I comment out the one of them, the other works.

file = string.replace(NAME,"-", "_")  
file = string.replace(NAME," ", "_")

I have also tried this:

test = (' ', '-')  
file = string.replace(NAME, test, "_")  

but no luck. I am using Python 2.7.
All tips welcome.

3
  • 1
    No, both replacements work. The first replaces and stores the result in a string called file. The second also replaces and also stores the result in file. At that point it overwrites the previous contents of the variable. No surprise there; x = 1 followed by x = 2 yields in x = 2, not x = 1 or 2 or any other previous value. Commented Mar 8, 2018 at 10:42
  • You're storing it in a different variable, which you aren't using in the next statement. Commented Mar 8, 2018 at 10:43
  • @usr2564301 : This worked! It seems obvious now when you say it but I was going around in circles. Commented Mar 8, 2018 at 11:23

2 Answers 2

2

This should help. Try chaining the replace method

string = "test-file 123.dwg"
file = string.replace("-", "_").replace(" ", "_")
print file  

Output:

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

Comments

0

Try this

x = "test-102"
x = x.replace('-', '_')
print(x)

test_102

The replace method should be called on your created string. Not the string class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.