Reputation: 35
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.
Upvotes: 0
Views: 123
Reputation: 91017
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]
.)
Upvotes: 2