-1

We have to create a totem pole using strings consisting of 13 characters wide. Each head must have different characteristics. Some of my functions for characteristics are below. However, when I ran my code it gave me the syntax error above.

import random

def hair_spiky():
        return"/\/\/\/\/\/\/"

def hair_middlepart():
        return"\\\\\\ //////"

def eye_crossed():
        a1= r" ____   ____"
        a2= r"/    \ /    \"
        a3= r"|   O| |O   |"
        a4= r"\____/ \____/"
        return a1 +"\n" + a2 + "\n" + a3 + "\n" a4
    def eye_left():
        a1=r" ____   ____"
        a2=r"/    \ /    \"
        a3=r"|O   | |O   |"
        a4=r"\____/ \____/"

2 Answers2

1

You cannot use a \ as the last character in a raw string literal:

r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character).

Don't use a raw string there; just double the backslashes instead:

a2= "/    \\ /    \\"

or use a raw multiline string by using triple quotes:

def eye_crossed():
    return r"""
 ____   ____
/    \ /    \
|   O| |O   |
\____/ \____/"""[1:]

def eye_left():
    return r"""
 ____   ____
/    \ /    \
|O   | |O   |
\____/ \____/"""[1:]

The slice is used to remove the initial newline which is part of the string.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

This is an odd quirk of raw strings, and is indicated by the syntax highlighting difference, see lexical analysis:

Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes)

To fix it use normal strings and/or concatenation:

 "/    \\ /    \\"
r"/    \ /    " + '\\'
user2864740
  • 60,010
  • 15
  • 145
  • 220