Python: What does backslash and a positive sign mean? - python-3.x

I am going thorough a code, I have seen different operators before, but "+ \" is a little but strange.
This is the line of the code:
self.spam_words + \
Does anyone know what this operator "+ \" means in python? i have c++ background
Th

\ if not followed by anything else tells the interpreter that the line does not end here, and it glues the next line to this one.
Its probably just to follow PEP 008 style guide 79 char limit and format stuff nicely.
test = "some" + \
"text"
print(test)
Output:
sometext
See https://www.python.org/dev/peps/pep-0008/#id19 and look for line continuation:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
The pep also tells you to break where it is possible w/o resorting to \, f.e.:
test = ["sometext_{}".format(a) # does not need a \
for a in range (200)]

Related

create a string with quotes and back slash using python

i would like to create a string in the following exact format :
"\"\"\"\nThis is a beautiful world.\n"
But the code :
test ="\"\"\"\nthis is a beautiful world.\n"
test
gives the output :
'"""\nthis is a beautiful world.'
please help in getting an exact text.
My string test should look exactly like the string it has been initialized to. but after initialization, it actually gives the output as mentioned. i want to concatenate the test string to another string
the symbol "\" is called an escape character in most programming languages. this is used to add symbols to a string that might not be easy to add. eg - to add a double quote into a string, we add the \" to the string. eg -
a = "he said, \"hello\" to me"
this would give the output as -
he said "hello" to me
here, the "\" acts as a symbol for the code which allows it to recognize characters which might raise errors other-wise.
to include a backslash in your code, add an extra backslash to it. eg -
a = "\\"
here, the value of a is \.
if you still haven't been able to understand it, try - this tutorial
for your code,try this -
test = "\\\"\\\"\\\"\\nThis is a beautiful world.\\n"
and if you also want the double quotes at the ends,
test = "\"\\\"\\\"\\\"\\nThis is a beautiful world.\\n\""
The first thing to note is, that just typing in the variable name when running python interactively returns the canonical string representation of the object and not (necessarily) the plain value of the object.
For strings this means (among other things) that quotes are added around the output (in your example the outermost single quotes) and any newlines are replaced with "\n".
This means that, although your output does show "\n" the actual string contains a newline character in its place.
The check what a string looks like, you should use the print() function to, well, print it.
>>> test = "\"\"\"\nthis is a beautiful world."
>>> test
'"""\nthis is a beautiful world.'
>>> print(test)
"""
this is a beautiful world.
>>>
Also, when running the code from a file, lines just containing variable names will not result in any output.
To answer the question
There are a few ways to handle that.
Assuming that the desired output is
"""\nThis is a beautiful world.\n
i.e. the outermost double quotes are not supposed to be part of the string, that is
While using double quotes ("…") to denote strings: escape any \ or " by prepending it with \:
>>> test ="\\\"\\\"\\\"\\nthis is a beautiful world.\\n"
>>> print(test)
\"\"\"\nthis is a beautiful world.\n
Within regular strings \ is used to designate control character. For example: \n is interpreted as newline, \b would be a backspace. If you need to have a \ in a string, you need actually write two \\.
If you are usually using "…" for string notation, this allows for a more consistent coding style but it is (especially in this case) quite ugly and might be hard to understand at a glance.
As your string contains a lot of " characters, just use single quotes ('…') to designate the string. This removes the need to escape ":
>>> test = '\\"\\"\\"\\nthis is a beautiful world.\\n'
>>> print(test)
\"\"\"\nthis is a beautiful world.\n
This is less consistent (if "…" is usually used for strings, but allows the code to be quite a bit closer to the desired output.
Use raw strings (r'…' or r"…") to disable the interpretation of control characters and allow the use of " within the string:
>>> test = r'\"\"\"\nthis is a beautiful world.\n'
>>> print(test)
\"\"\"\nthis is a beautiful world.\n"
or even
>>> test = r"\"\"\"\nthis is a beautiful world.\n"
>>> print(test)
\"\"\"\nthis is a beautiful world.\n"
This allows the code to be identical to the desired output, but it has some limitations when it comes to freely mixing " and ' within a single string as it is not possible to escape the quotation marks within the string without also adding \ to the string output. This can be seen in the second example, where we use \" to escape the double quote within r"…" in the code but where the \s are still present in the output. While this works well in this specific case, I would recommend against using \' within r'…' or \" within r"…" to avoid confusion.

How do you add a single backslash to a string in Golfscript?

I'm having a bit of an issue trying to do an ascii art challenge in GS, since it requires you finishing a line with the \ symbol.
The problem is that "\"p breaks the program since it thinks you escaped a quote, and "\\"p prints two backslashes. I've tried string concatenation, removing one character at a time, printing substrings, etcetc - Nothing seems to work!
I need this string to be printed out, so how would this be done?
It seems that the behavior with p is buggy. I'll look for a place to report it.
However, "\\" by itself does not print two backslashes; it prints one.
Here's a test link to prove it.
Output:
\
"\\" creates a string with 1 backslash because strings are escaped. This is the same as languages like Ruby.
p escapes strings, so a string with one backslash will be displayed as two. This is also the same as languages like Ruby.
So if you want to print a single backslash, or print things without the quotes, you need to print unescaped strings. The best way to do this is with implicit IO (anything on the stack that is left over is printed unescaped).
The program
"\\"
Should print
\
You could also use print or puts if you don't want to use implicit IO.

How to break a string over multiple lines and preserve spaces in YAML?

Please note, that the question is similar like this one, but still different so that those answers won't solve my problem:
For insertion of control characters like e.g. \x08, it seems that I have to use double quotes ".
All spaces needs to be preserved exactly as given. For line breaks I use explicitly \n.
I have some string data which I need to store in YAML, e.g.:
" This is my quite long string data "
"This is my quite long string data"
"This_is_my_quite_long_string_data"
"Sting data\nwhich\x08contains control characters"
and need it in YAML as something like this:
Key: " This is my" +
" quite long " +
" string data "
This is no problem as long as I stay on a single line, but I don't know how to put the string content to multiple lines.
YAML block scalar styles (>, |) won't help here, because they don't allow escaping and they even do some whitespace stripping, newline / space substitution which is useless for my case.
Looks that the only way seems to be using double quoting " and backslashes \, like this:
Key: "\
This is \
my quite \
long string data\
"
Trying this in YAML online parser results in "This is my quite long string data" as expected.
But it unfortunately fail if one of the "sub-lines" has leading space, like this:
Key: "\
This is \
my quite\
long st\
ring data\
"
This results in "This is my quitelong string data", removed the space between the words quite and long of this example. The only thing that comes to my mind to solve that, is to replace the first leading space of each sub-line by \x20 like this:
Key: "\
This is \
my quite\
\x20long st\
ring data\
"
As I'd chosen YAML to have a best possible human readable format, I find that \x20 a bit ugly solution. Maybe someone know a better approach?
For keeping human readable, I also don't want to use !!binary for this.
Instead of \x20, you can simply escape the first non-indentation space on the line:
Key: "\
This is \
my quite\
\ long st\
ring data\
"
This works with multiple spaces, you only need to escape the first one.
You are right in your observation that control characters can only be represented in double quoted scalars.
However the parser doesn't fail if the sub-lines (in YAML speak: continuation lines) have a leading space. It is your interpretation of the YAML standard that is incorrect. The standard explicitly states that for multi-line double quoted scalars:
All leading and trailing white space characters are excluded from the content.
So you can put as many spaces as you want before long as you want, it will not make a difference.
The representer for double quoted scalars for Python (both in ruamel.yaml and PyYAML) always does represent newlines as \n. I am not aware of YAML representers in other languages where you have more control over this (and e.g. get double newlines to represent \n in your double quoted scalars). So you probably have to write your own representer.
While writing a representer you can try to make the line breaking be smart, in that it minimizes the number of escaped spaces (by putting them between words on the same line). But especially on strings with a high double space to word ratio, combined with a small width to operate in, it will be hard (if not impossible) to do without escaped spaces.
Such a representer should IMO first check if double quoting is necessary (i.e. there are control characters apart from newlines). If not, and there are newlines you are probably better of representing the string a block style literal scalar (for which spaces at the beginning or end of line are not excluded).

Putting "\n" in my .c or .cpp file using vim

I'm using vim to make my programs in c/c++ and I would like to know how can I put "\n" (which represents a newline) in my code or use "%" using :%s.
For instance, sometimes I forget to put "%" in front of "d" or "f" in many lines or forget to put "\n" in some printf() calls.
printf("This is my d code.", x);
But the following command does not work, it puts a space in place of "\n"!
:%s/\<code.\>/code.\n/gc
or
:%s/\<d\>/%d/gc
How can I do what I want?
The :help s/\n has the answer:
\n insert a <NL> (<NUL> in the file)
(does NOT break the line) *s/\n*
You'll also find the solution there: to insert a literal backslash, escape it \\ by doubling; to split the line, a \r has to be used. Yes, this is inconsistent, and it works differently in similar tools like sed, but that's unfortunately how it is.
Notes
The \n doesn't insert a space, but the special <NL> character, which usually is shown as ^#.
The \<code.\> isn't right; to match a literal period, you have to escape it: \.. Else, it matches any character. Likewise, the . usually isn't a keyword character, so the \> boundary wouldn't match.
You don't need to repeat the match text in the replacement, you can use & for it. Also read up on capture groups (:help /\() and the submatch references :help s/\1. This is a better way:
:%s/\<code\./&\\n/gc
(I don't see a problem with the second substitution.)
You want to insert the two-character sequence \n, not a literal newline (the latter would create a syntax error).
A sample line to be changed is:
printf("This is my d code.", x);
One problem with your attempt:
:%s/\<code.\>/code.\n/gc
is that there is no word boundary between the . and the " following the word code. The other problem is that \ in the target is used to escape special characters (for example you can refer to a / character as \/), so the \ must itself be escaped.
This should do the job:
:%s/\<code\."/code.\\n"/gc
A more general solution might be:
:g/printf/s/"/\\n"/egc
which offers to replace " by \n" on each line that contains printf -- but that will miss any printf calls that span more than one line.
As for replacing the d by %d, the command you have in your question:
:%s/\<d\>/%d/gc
is correct.

Could not able to replace \" with " in html tags using C#

I want to replace a as using C#. I could not able to achive this using Regex.Replace functions as follos
Regex.Replace(html, "\\"", "\"");
execution this command again produces the original output
Anyone have already faced issue like this,Any help would be of greatly appreciated.
Regards,
Ganesan
first of all "\\""produces a compiler error, since you are just escaping one backslash but not the quote.
you are working with 2 escape mechanisms here, one is from the c# compiler, and another is from the regex interpreter.
Which means:
when you give this C# string as a regex: "\\\"" then after compilation there is a string looking like that \", which is then interpreted by the regex engine, which also uses \ as the escape character. therefor regex will escape ", so your code will replace " with "
so if you now use "\\\\\"", first the c# compiler will make \\" out of that, then the regex engine will make \" out of that (both are using \ as escape character)
now c# has a nice little feature to make such strings easier to write.
if you add an # before your string, \ will no long be the escape character, but now you have to escape " with ""
that means "\\\"" == #"\""" and "\\\\\"" == #"\\"""
so you could write Regex.Replace(html,#"\\""","\"")
which is easier to read then Regex.Replace(html,"\\\\\","\"")
i think i got it right this time :D

Resources