Search code examples
pythonappendpython-re

Additional character "\" present when appending strings into a list python


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

  • 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('\\')
    \