我正在将文件从一个文件夹复制到另一个文件夹中。这些文件包含短划线' - '和空间' ' 。例如,测试文件123.dwg 我需要用下划线替换这些连字符和空格,所以它看起来像 test_file_123.dwg
我试过这个,它取代了连字符,但没有空格。如果我注释掉其中一个,那么另一个就可以了。
file = string.replace(NAME,"-", "_")
file = string.replace(NAME," ", "_")
我也试过这个:
test = (' ', '-')
file = string.replace(NAME, test, "_")
但没有运气。 我使用的是Python 2.7 欢迎所有提示。
答案 0 :(得分:2)
这应该有所帮助。尝试链接replace
方法
string = "test-file 123.dwg"
file = string.replace("-", "_").replace(" ", "_")
print file
<强>输出:强>
test_file_123.dwg
答案 1 :(得分:0)
试试这个
1.141592...
test_102
应该在创建的字符串上调用replace方法。不是字符串类。