tadm123 tadm123 - 20 days ago 8
Python Question

Getting only one '\' character when joining a list

I want to have a string with the

'\w'
character after each letter.

For example:

my_string = 'asdfg'


What I want:

my_string = 'a\ws\wd\wd\wf\wg\w'


Now, how I approached this is first storing each letter into a list:

list=[]
for i in my_string:
list.append(i)


And then joining it with a
\w
character in between to form my new string. However, I ran into some problems.

'\w'.join(list)


I'm getting a double backslash character instead of one:

'q\\ww\\we\\wr\\wt\\wy\\wu\\wy\\wt\\wr\\we\\ws\\wd\\wf\\wt\\wy\\wu\\wi\\wo\\wk\\wn\\wn'


I'd greatly appreciate any help in fixing this. Thanks.

Answer

\w is not a character. You might be thinking of another escape character, but '\w' simply evaluates to '\\w', since \w just doesn't exist.

Oh, you might also want to replace your for loop with simply list(my_string) or tuple(my_string) - or even the entire thing with '[whatever character you actually wanted]'.join(my_string) - it's simpler and does the same thing. To get your expected result, you'll also need to add the character to the end of the string, as in '[x]'.join(my_string) + '[x]'. As it stands now, you won't get the character after the very last letter.

Comments