I'd like to error-proof user input to a file reading function. Suppose the user input string has backslashes sqlfile_in_DS="I:\DS\40-400\OppMetrics.sql"
and I want the corrected string to replace those with forward slashes sqlfile_in_DS="I:/DS/40-400/OppMetrics.sql"
. In my attempts, the substring "/40" disappears.
Attempts and results:
1) print(pathlib.PureWindowsPath(sqlfile_in_DS))
OUTPUT:
I:/DS -400/OppMetrics.sql
2) print(sqlfile_in_DS.replace('\\','/'))
OUTPUT:
I:/DS -400/OppMetrics.sql
I used the answers from [Replace Backslashes with Forward Slashes in Python], Converting a string variable to a regular expression in python
If the string is a raw string literal both methods work:
sqlfile_in_DS=r"I:\DS\40-400\OppMetrics.sql"
print(pathlib.PureWindowsPath(sqlfile_in_DS))
print(sqlfile_in_DS.replace('\\', '/'))
OUTPUT:
I:/DS/40-400/OppMetrics.sql
I can't find a good explanation for converting a simple string to a raw string that works. Python regex: How to search and replace strings doesn't
print(sqlfile_in_DS.encode('unicode_escape'))
OUTPUT:
b'I:\\\\DS -400\\\\OppMetrics.sql'
print(r'{}'.format(sqlfile_in_DS))
OUTPUT:
I:\DS -400\OppMetrics.sql