0

In my code i have a list of locations and the output of a list is like this

['D:\\Todo\\VLC\\Daft_Punk\\One_more_time.mp4"', ...

i want a replace "\\" with "\" (listcancion is a list with all strings) i try to remplace with this code remplacement = [listcancion.replace('\\', '\') for listcancion in listcancion] or this remplacement = [listcancion.replace('\\\\', '\\') for listcancion in listcancion] or also this remplacement = [listcancion.replace('\\', 'X') for listcancion in listcancion] listrandom = [remplacement.replace('X', '\') for remplacement in remplacement]

I need to change only the character \ i can't do it things like this ("\\Todo", "\Todo") because i have more characters to remplace.

If i can solved without imports thats great.

tortuga445
  • 35
  • 1
  • 1
  • 5
  • 4
    Those already are single backslash characters. You don't need to do any replacement. You're just not yet familiar with how `repr` and escaping work, so you're getting confused by how the list is displayed. – user2357112 Nov 22 '19 at 09:34
  • The backslash is an escape character in Python. – wallisers Nov 22 '19 at 09:35
  • Possibly duplicate of https://stackoverflow.com/questions/5186839/python-replace-with – krishnakant Nov 22 '19 at 09:47
  • @krishnakant No, that deals with a slightly different issue, AFAICT. Or at least, on a different level. – glglgl Nov 22 '19 at 09:49

1 Answers1

2

It is just a matter of string representations.

First, you have to differentiate between a string's "real" content and its representation.

A string's "real" content might be letters, digits, punctuation and so on, which makes displaying it quite easy. But imagine a strring which contains a, a line break and a b. If you print that string, you get the output

a
b

which is what you expect.

But in order to make it more compact, this string's representation is a\nb: the line break is represented as \n, the \ serving as an escape character. Compare the output of print(a) (which is the same as print(str(a))) and of print(repr(a)).

Now, in order not to confuse this with a string which contains a, \, n and b, a "real" backslash in a string has a representation of \\ and the same string, which prints as a\nb, has a representation of a\\nb in order to distinguish that from the first example.

If you print a list of anything, it is displayed as a comma-separated list of the representations of their components, even if they are strings.

If you do

for element in listcancion:
    print(element)

you'll see that the string actually contains only one \ where its representation shows \\.

(Oh, and BTW, I am not sure that things like [listcancion.<something> for listcancion in listcancion] work as intended; better use another variable as the loop variablen, such as [element.<something> for element in listcancion].)

glglgl
  • 89,107
  • 13
  • 149
  • 217