-1

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)
Kewei
  • 15
  • 7
  • The difference is merely that the single string simply prints its contents, while printing the list gives you a *repr* of the entire list. Note that one string has quotes and the other doesn’t. – deceze Apr 29 '22 at 05:31
  • So are the values in the list actually having double backslash? I will be using this list for file search so having double backslash will change the meaning entirely. @deceze – Kewei Apr 29 '22 at 05:37
  • You need to understand the difference between the string’s contents, and a **representation** of the string as a literal, i.e. what you’d need to type into your source code to obtain that string! The list gives you the latter; again: notice the surrounding quotes. – deceze Apr 29 '22 at 05:57

1 Answers1

0

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('\\')
\
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
  • I did, but the result is still showing double backslash @Mechanic Pig – Kewei Apr 29 '22 at 05:25
  • @Kewei This is a normal phenomenon. The backslash must be represented by two backslashes in the string, but if you print it out, you won't see two. – Mechanic Pig Apr 29 '22 at 05:28