user12711263
user12711263

Reputation:

How could I insert backslash into this python string?

I have a list of strings which looks like this: B = [' _ ', '|_\', '|_/']

(if you put these strings on top of each other you get the character B).

So I have this list of strings but Visual Studio Code says that this string literal is not terminated...

I assume it means the second element in the list as it has a backslash. What can I do about it? I tried double backslash, but then it just prints double backslash if I print the line

Thanks in advance

Upvotes: 0

Views: 438

Answers (2)

Luke_
Luke_

Reputation: 805

So i assume your code looks something like this:

def func(str):
    print("\n".join(str))

A = [' _ ', '|_|', '| |']
B = [' _ ', '|_\'', '|_/']
C = [' _ ', '|  ', '|_ ']
D = [' _ ', '| \'', '|_/']
E = [' _ ', '|_ ', '|_ ']
F = [' _ ', '|_ ', '|  ']

func(A)
func(B)
func(C)
func(D)
func(E)
func(F)


This gives us this output:

 _ 
|_'
|_/

I assume the output you are looking for is more like this:

_ 
|_\
|_/

You want that ' to be gone and replaced with , this doesnt mean the string is not terminated, it means that you escaped a quote. Lets take a look at the string that has this error, its the second string in the B array:

'|_''

first it prints a | then it prints a _ and then it prints a ' (a quote which is escaped using a backslash)

We do not want to do this because we dont want to print a quote, but want to print a backslash character. this is done by escaping a backslash using a backslash (so you end up with a double backslash) \

So the correct B array should be:

B = [' _ ', '|_\\', '|_/']

You also appear to have made a similair mistake in D which should be D = [' _ ', '| \'', '|_/']

Upvotes: 3

Richárd Baldauf
Richárd Baldauf

Reputation: 1118

You have to escape the escape character \' results ' as string and \\ results \ as string:

B = [' _ ', '|_\\', '|_/']
n = len(B)
for i in range(n):
    print(B[i])

Upvotes: 0

Related Questions