I am having problems with this Python program I am creating to do maths, working out and so solutions but I'm getting the syntaxerror: "unexpected character after line continuation character in python"
this is my code
print("Length between sides: "+str((length*length)*2.6)+" \ 1.5 = "+str(((length*length)*2.6)\1.5)+" Units")
My problem is with \1.5 I have tried \1.5 but it doesn't work
Using python 2.7.2
The division operator is /, not \
The backslash \ is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the "interrupted" line.
print "This is a very long string that doesn't fit" + \
"on a single line"
Outside of a string, a backslash can only appear in this way. For division, you want a slash: /.
If you want to write a verbatim backslash in a string, escape it by doubling it: "\\"
In your code, you're using it twice:
print("Length between sides: " + str((length*length)*2.6) +
" \ 1.5 = " + # inside a string; treated as literal
str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
# character, but no newline follows -> Fail
" Units")
You must press enter after continuation character
Note: Space after continuation character leads to error
cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}
0.9 * average(cost["apples"]) + \ """enter here"""
0.1 * average(cost["bananas"])
The division operator is / rather than \.
Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:
"\\ 1.5 = "`
or use a raw string
r" \ 1.5 = "
Well, what do you try to do? If you want to use division, use "/" not "\".
If it is something else, explain it in a bit more detail, please.
As the others already mentioned: the division operator is / rather than **.
If you wanna print the ** character within a string you have to escape it:
print("foo \\")
# will print: foo \
I think to print the string you wanted I think you gonna need this code:
print("Length between sides: " + str((length*length)*2.6) + " \\ 1.5 = " + str(((length*length)*2.6)/1.5) + " Units")
And this one is a more readable version of the above (using the format method):
message = "Length between sides: {0} \\ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))
This is not related to the question; just for future purpose. In my case, I got this error message when using regex. Here is my code and the correction
text = "Hey I'm Kelly, how're you and how's it going?"
import re
When I got error:
x=re.search(r'('\w+)|(\w+'\w+)', text)
The correct code:
x=re.search(r"('\w+)|(\w+'\w+)", text)
I'm meant to use double quotes after the r instead of single quotes.
Related
Can't we use \t and \n in variables?
var1 = " Ryan "
print (\tvar1.strip() + \nvar1.lstrip() + \nvar1.rstrip())
I get an error:
syntax error : unexpected character after line continuation character
You need to treat them as regular characters and concatenate them properly with other strings:
print('\t' + var1.strip() + '\n' + var1.lstrip() + '\n' + var1.rstrip())
(edit from ShadowRanger's comments):
If you are on Python 3.6+, you can use f-strings instead of the + operator:
print(f"\t{var1.strip()}\n{var1.lstrip()}\n{var1.rstrip()}")
If you can't use f-strings yet, you can use the regular str.format method:
print("\t{}\n{}\n{}".format(var1.strip(), var1.lstrip(), var1.rstrip()))
You can also include them directly in literal strings:
str1 = "\tabc\ndef"
when I type this code in python it shows this error
>>> 'Ahmed' + \t 'Ashraf '
SyntaxError: unexpected character after line continuation character
what does this error mean ??
The \t escape sequence has to be inside a string literal, so the correct syntax is:
'Ahmed' + '\t' + 'Ashraf '
Outside a string literal, \ is used to indicate that you're continuing a statement on the next line, so it's called the line continuation character. It should only be followed by a newline, e.g.
>>> var1 = 'Ahmed' + \
'Ashraf'
If it's followed by some other character, such as t in your example, you get an error.
You can also do it with the format string.
>>> '%s\t%s' %('Ahmed','Ashraf')
'Ahmed\tAshraf'
>>>
I am coming from C language
In book of Python it is given
among escape sequence
\ - New line in a multi-line string
\n - Line break
I am confused and unable to differentiate between the two.
You have completely misread the book.
\ is not an escape sequence, and is not used on its own in strings. It is used in multi-line code.
\n is a newline character in strings.
The book is confusing you by mixing two entirely different concepts.
\n is an escape sequence in a string literal. Like other \single-character and \xhh or \uhhhh escape sequences these work exactly like those in C; they define a character in the string that would otherwise be difficult to spell out when writing code.
\ at the end of a physical line of code extends the logical line. That is, Python will see text on the next line as part of the current line, making it one long line of code. This applies anywhere in Python code.
You can trivially see the difference when you print the results of strings that use either technique:
escape_sequence = "This is a line.\nThis is another line"
logical_line_extended = "This is a logical line. \
This is still the same logical line."
print(escape_sequence)
print(logical_line_extended)
This outputs
This is a line.
This is another line
This is a logical line. This is still the same logical line.
Note that the line breaks have swapped! The \n escape sequence in the string value caused the output to be broken across two lines (the terminal or console or whatever is displaying the printed data, knows how to interpret a newline character), while the newline in the logical_line_extended string literal definition is gone; it was never part of the string value being defined, it was a newline in the source code only.
Python lets you extend a line of code like this because Python defines how you delimit logical lines very differently from C. In C, you end statements with ;, and group blocks of lines with {...} curly braces. Newlines are not part of how C reads your code.
So, the following C code:
if (a) { foo = 'bar'; spam = 'ham'; }
is the same thing as
if (a) {
foo = 'bar';
spam = 'ham';
}
C knows where each statement starts and ends because the programmer has to use ; and {...} to delimit lines and blocks, the language doesn't care about indentation or newlines at all here. In Python however, you explicitly use newlines and indentation to define the same structure. So Python uses whitespace instead of {, } and ;.
This means you could end up with long lines of code to hold a complex expression:
# deliberately convoluted long expression to illustrate a point
expr = 18 ** (1 / 3) / (6 * (3 + sqrt(3) * I) ** (1 / 3)) + 12 ** (1 / 3) * (3 + sqrt(3) * I) ** (1 / 3) / 12
The point of \ is to allow you to break up such a long expression across multiple logical lines by extending the current line with \ at the end:
# deliberately convoluted long expression to illustrate a point
expr = 18 ** (1 / 3) / (6 * (3 + sqrt(3) * I) ** (1 / 3)) + \
12 ** (1 / 3) * (3 + sqrt(3) * I) ** (1 / 3) / 12
So the \ as the last character on a line, tells Python to ignore the newline that's there and continue treating the following line as part of the same logical line.
Python also extends the logical line when it has seen an opening (, [ or { brace, until the matching }, ] or ) brace is found to close the expression. This is the preferred method of extending lines. So the above expression could be broken up across multiple logical lines with:
expr = (18 ** (1 / 3) / (6 * (3 + sqrt(3) * I) ** (1 / 3)) +
12 ** (1 / 3) * (3 + sqrt(3) * I) ** (1 / 3) / 12)
You can do the same with strings:
long_string = (
"This is a longer string that does not contain any newline "
"*characters*, but is defined in the source code with "
"multiple strings across multiple logical lines."
)
This uses another C string literal trick Python borrowed: multiple consecutive string literals form one long string object once parsed and compiled.
See the Lexical analysis reference documentation:
2.1.5. Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (\)[.]
[...]
2.1.6. Implicit line joining
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes.
The same documentation lists all the permitted Python string escape sequences.
\ - New line in a multi-line string
It is used for splitting a string which has a vast number of characters into multi lines as it is inconvenient to write in a single line.
This is something that has effect in the code only.
\n - Line break
This one on the other hand is a typical line break statement for printing something in a new line. The same thing we use in C and C++ languages.
this is something that has effect in the output.
Here is the response to your question:
Purpose of \n is basically used to give a line break as you mention too.
Example:
print("Hello\n")
print("Hi")
The output of the above would be like:
Hello
Hi
Purpose of \ is basically used to escape characters which have special meaning
Example: I have to print Hello\ in the output then the code will be like
print("Hello\\")
The output of the above code will be like:
Hello\
So bascially in order to print Hello\ in your output, you have to put two "\\" and this is the purpose of \ character (to escape special characters).
I hope this helps.
With "\" you can change line as you write your code. What I mean is that if you write a long line of code and you want to change line to see what you type.
For example :
print("This is a demonstration of backslash.")
is the same as writing :
print("This is a demonstration \
of backslash")
On the other hand with "\n" you can change line in what you want to print. For example, when you write:print("this is an \nexample"), it will print "this is an"(changes line) "example".
Use \n to have your output go to the next line.
print('Hello \nworld!')
Hello
world!
Use the back slash with a character that has a meaning to Python when you want that character to appear in the printed output.
print('It\'s cold outside')
It's cold outside
I hope this helps. 😀
As excellently answered by #Jimmy I further give the following examples to make the matter more clear.
Case 1:
>>> var1 = "Adolf Hitler was a German dictator. He started the second world war."
>>> print(var1)
Adolf Hitler was a German dictator. He started the second world war.
>>>
Case 2:
>>> var2 = "Adolf Hitler\
... was a German dictator.\
... He started the\
... second world war."\
...
>>> print(var2)
Adolf Hitler was a German dictator. He started the second world war.
>>>
Case 3:
>>> var3 = "Adolf Hitler\nwas a German dictator.\nHe started the\nsecond world war."
>>> print(var3)
Adolf Hitler
was a German dictator.
He started the
second world war.
>>>
Case 4:
>>> var4 = "Adolf Hitler\
... \nwas a German dictator.\
... \nhe started the\
... \nsecond world war."\
...
>>> print(var4)
Adolf Hitler
was a German dictator.
he started the
second world war.
>>>
There is also another point which #Jimmy has not mentioned. I have illustrated it by the following two examples -
Example 1:
>>> var5 = """
... This multi-line string
... has a space at the top
... and a space at the bottom
... when it prints.
... """
>>> print(var5)
This multi-line string
has a space at the top
and a space at the bottom
when it prints.
>>>
Example 2:
>>> var6 = """\
... This multi-line string
... has no space at the
... top or the bottom
... when it prints.\
... """
>>> print(var6)
This multi-line string
has no space at the
top or the bottom
when it prints.
I am very new to Python. I am constructing a string that is nothing but a path to the network location as follows. But it outputs the error: "Python unexpected character after line continuation character". Please help. I saw this post but I am not sure if it applies to my scenario:
syntaxerror: "unexpected character after line continuation character in python" math
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
One of your \ backslashes escapes the " double quote following it. The rest of the string then ends just before the next \ backslash, and that second backslash is seen as a line-continuation character. Because there's another " right after that you get your error:
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
# ^^ not end of string ||
# ^--- actual string ---^||
# line continuation /|
# extra character /
You need to double those backslashes:
s_path_publish_folder = r"\\" + s_host + "\\" + s_publish_folder "\\" + s_release_name
Better yet, use the os.path module here; for example, you could use os.path.join():
s_path_publish_folder = r"\\" + os.path.join(s_host, s_publish_folder, s_release_name)
or you could use string templating:
s_path_publish_folder = r"\\{}\{}\{}".format(s_host, s_publish_folder, s_release_name)
I am looking for a way to prefix strings in python with a single backslash, e.g. "]" -> "]". Since "\" is not a valid string in python, the simple
mystring = '\' + mystring
won't work. What I am currently doing is something like this:
mystring = r'\###' + mystring
mystring.replace('###','')
While this works most of the time, it is not elegant and also can cause problems for strings containing "###" or whatever the "filler" is set to. Is there a bette way of doing this?
You need to escape the backslash with a second one, to make it a literal backslash:
mystring = "\\" + mystring
Otherwise it thinks you're trying to escape the ", which in turn means you have no quote to terminate the string
Ordinarily, you can use raw string notation (r'string'), but that won't work when the backslash is the last character
The difference between print a and just a:
>>> a = 'hello'
>>> a = '\\' + a
>>> a
'\\hello'
>>> print a
\hello
Python strings have a feature called escape characters. These allow you to do special things inside as string, such as showing a quote (" or ') without closing the string you're typing
See this table
So when you typed
mystring = '\' + mystring
the \' is an escaped apostrophe, meaning that your string now has an apostrophe in it, meaning it isn't actually closed, which you can see because the rest of that line is coloured.
To type a backslash, you must escape one, which is done like this:
>>> aBackSlash = '\\'
>>> print(aBackSlash)
\
You should escape the backslash as follows:
mystring = "\\" + mystring
This is because if you do '\' it will end up escaping the second quotation. Therefore to treat the backslash literally, you must escape it.
Examples
>>> s = 'hello'
>>> s = '\\' + s
>>> print
\hello
Your case
>>> mystring = 'it actually does work'
>>> mystring = '\\' + mystring
>>> print mystring
\it actually does work
As a different way of approaching the problem, have you considered string formatting?
r'\%s' % mystring
or:
r'\{}'.format(mystring)