-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.

FelixSFD
  • 6,052
  • 10
  • 43
  • 117
user28849
  • 71
  • 1
  • 5
  • 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`. – Jongware Mar 08 '18 at 10:42
  • You're storing it in a different variable, which you aren't using in the next statement. – Zeokav Mar 08 '18 at 10:43
  • @usr2564301 : This worked! It seems obvious now when you say it but I was going around in circles. – user28849 Mar 08 '18 at 11:23

2 Answers2

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
Rakesh
  • 81,458
  • 17
  • 76
  • 113
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.

JahKnows
  • 2,618
  • 3
  • 22
  • 37