tadm123 tadm123 - 8 months ago 38
Python Question

Getting only one '\' character when joining a list

I want to have a string with the

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:

for i in my_string:

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


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


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


\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.