'Additional character "\" present when appending strings into a list python [duplicate]
does anyone encountered this issue whereby when a string containing "\" is appended into a list, the function adds an additional "\" into the string?
file_list = ['file1.txt','file2.txt','file3.txt']
res = []
for i in range(len(file_list)):
filename = file_list[i].replace(".", "\.")
print(filename)
res.append(filename)
print(res)
print(res)
The result that I got from running the above was:
file1\.txt
['file1\\.txt']
file2\.txt
['file1\\.txt', 'file2\\.txt']
file3\.txt
['file1\\.txt', 'file2\\.txt', 'file3\\.txt']
['file1\\.txt', 'file2\\.txt', 'file3\\.txt']
I want to get the following result instead:
['file1\.txt', 'file2\.txt', 'file3\.txt']
UPDATE
Ran the following code, still get the same output as above. Question not answered, but closed?
file_list = ['file1.txt','file2.txt','file3.txt']
res = []
for i in range(len(file_list)):
filename = file_list[i].replace(".", "\\.")
print(filename)
res.append(filename)
print(res)
print(res)
Solution 1:[1]
This is a normal phenomenon. The backslash in Python is used to escape characters. To directly represent the backslash, you need to use two:
>>> len('\\')
1
>>> print('\\')
\
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mechanic Pig |
