How to share python code in stackoverfolw? [migrated] - python

How do I post text so that it is formatted as code?
What do I need to do so that my code shows up properly—not escaped or removed—when posted? And how do I get the correct syntax highlighting?
For more information, see "How do I format my posts in HTML or Markdown?" in the Help Center.
Return to FAQ index

For inline code (that does not hold newlines), any of the following will work:
Enclose with backticks: `<html>`.
Embed within <code> tags, and manually encode HTML entities: <code><html></code>
Select the partial text and hit CtrlK (⌘K on OS X) or click the {} button above the editor (pictured below)
For blocks of code, to preserve newlines, use one of the following methods:
Use the {} button above the editor (pictured below)
Paste your code, select the full lines, and hit CtrlK (⌘K on OS X)
Use fenced code blocks by surrounding your code with ``` or with ~~~
Opening and closing fence have to be on their own line, and can be indented with up to three spaces
More than three backticks or tildes can be used, as long as the closing fence uses the same character and is at least as long as the opening fence
Indent everything four (4) spaces or one (1) tab
Ensure there is a blank line between the top of the block and other text
Encase in <pre> or <pre><code> tags (in that order; using <code><pre> is invalid), and encode HTML entities (like < for <) yourself
In <pre> blocks, HTML tags are applied rather than rendered as text. But in <pre><code> blocks with Syntax highlighting (see below), all HTML tags are stripped out. A lang-none language hint (see below) prevents syntax highlighting and keeps HTML tags.
(Code highlighting is disabled by default on meta sites.)
Code copy/pasted from an IDE is often already tabbed. When rendering, tabs are replaced with spaces.
Code within a blockquote
To include code within a blockquote, make sure to include the space after the > as well as the four spaces before the code.
> Lorem ipsum dolor sit amet, consectetur adipiscing elit.
> for(;;)
echo 'badger ';
Or, put the blockquote character (and its following space) at the beginning of every blank line, including the one immediately before the code.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
>
for(;;)
echo 'badger ';
You can also use fenced code blocks within quotes:
> Text before code
> ```
> for (;;;)
> echo 'badger';
> ```
> Text after code
Code within a numbered or bulleted list
If your code appears inside a list, you must indent an additional four spaces for each level of nesting.
- First bullet (is the deepest)
for(;;)
echo 'ow ';
- Second bullet
If you want a block of code to follow a list but not be nested under the final list item, you can use an HTML comment as a "breakpoint". If you do this, the code block only needs to be indented with the normal four spaces:
- First bullet
- Second bullet
<!-- -->
for(;;)
echo 'ow ';
Syntax highlighting
Highlight.js is used to add colour to the code, but only if the language can be uniquely determined given the tags of the question, or if manual hints have been provided.
For any code block, you can use these HTML comments to specify the language:
<!-- language: lang-or-tag-here -->
code goes here
<!-- language: lang-or-tag-here -->
code goes here
<!-- language: lang-or-tag-here -->
```
code goes here
```
<!-- language: lang-or-tag-here -->
~~~
code goes here
~~~
You can also specify the syntax for all codeblocks in your post with the language-all hint:
<!-- language-all: lang-or-tag-here -->
code goes here
More text not in code blocks
code goes here
Alternatively, if you use fenced code blocks, you can specify the language right after the first fence:
```lang-or-tag-here
code goes here
```
~~~lang-or-tag-here
code goes here
~~~
This goes for fenced code blocks elsewhere as well:
> ```javascript
> for (;;;) {
> console.log('badger');
> }
> ```
See the full specification and list of languages hints.
Note that:
The HTML comments must not be indented
The blank line between <!-- language: ... --> and the indented code block is required
The space between language: and the language is required
When using a tag to specify language, the tag name is case-sensitive
If you combine the fenced style with the HTML comments, the HTML comments are ignored
If no language is defined then no highlighting occurs at all. But in the preview, or if multiple language tags define very different languages and no manual definition is used, a default highlighting is used in which Prettify makes a best guess.
There is a delay before the preview text highlighting is applied after you stop editing your markdown source, of around 5 seconds.
Stack Snippets – Executable JavaScript/HTML/CSS snippets
Stack snippets can group a JavaScript, HTML and CSS code snippet and make them runnable. This feature can be accessed by the icon that looks like a page with a <> on it. Alternatively, you can press CtrlM (⌘M on OS X).
The code snippet tool allows you to format code automatically using the Tidy button on the left. You can use this option to take care of replacing tabs by spaces, correct code indentation, and general improvement of readability
Once you save your snippet, you’ll get something like this in the editor:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// JavaScript code
<!-- language: lang-css -->
/* CSS code */
<!-- language: lang-html -->
HTML code
<!-- end snippet -->
If you delete the begin snippet and end snippet comments, you’re left with three adjacent code snippets that are not executable. You may also keep a single block of code which will have the correct formatting and indentation.
Using mobile devices
One sometimes needs to press and hold the regular single quote to get the backtick.
Backticks in text
To include a backtick without accidentally starting some inline code, escape it: \`
like \` so yields: like ` so
<kbd>Alt Gr</kbd>+<kbd>\`</kbd> gets `|` yields: Alt Gr+` gets |
Backticks within backticks
To use literal backticks within a code span, use any unique number of multiple backticks as the opening and closing delimiters: both ``literal backtick (`) here`` and, for example, ``````literal backtick (`) here`````` yield literal backtick (`) here. This works in comments too.
To use literal backticks at the start and/or end, add one space to both the opening and closing delimiters: `` `<html>` `` yields `<html>`, and `` $` `` yields the Perl $` operator. In comments, the additional space in the delimiters is not supported. Instead, escape the backtick: `\`<html>\`` and `$\`` to get `<html>` or $` in a comment.

Related

Add HTML linebreaks with Python regex

I need to add HTML linebreaks (<br />) to a string at all line endings which are not followed by a blank line. This simple pattern works:
body = re.sub(r'(.)\n(.)', r'\1<br />\2', body)
But I realized it will not work for an edge case where a line contains only a single character (because the character would have to be part of two different overlapping matches). So I tried the following pattern with lookaround subpatterns:
body = re.sub(r'(?<=.)\n(?=.)', r'<br />', body)
This works as intended, except that the HTML tag is added after the linebreak (\n), and with an additional linebreak:
linebreak
<br/>
!
<br/>
linebreak
<br/>
l
<br/>
works
I would expect that the matched linebreak is substituted by the HTML tag (thereby effectively removing the linebreaks from all matching areas) – why does the tag appear on a new line instead (i.e. increasing the number of linebreaks/lines)?
The equivalent pattern in vim does remove the linebreaks:
s:\(.\)\zs\n\ze\(.\):\<br \/\>:ge
This is quite embarrassing – the pattern/my script do indeed work as supposed to. I was fooled by an HTML source viewer which obviously adds linebreaks to the source code it should display unaltered. Sorry for taking your valuable time.

How to insert indents into html code tag?

I'm trying to put some python code in html document. I am using code tag. Example
<code>
for iris, species in zip(irises, classification):
if species == 0:
print(f'Flower {iris} is Iris-setosa')
</code>
The problem is, page doesn't see new lines and indents. I can handle new lines with br tag but I didn't find anything to make indent. I tried pre tag, but I have to remove all indents in html document, and with several indents in it, it starts to look very ugly. Propably I could use but using 4,8 or 12 in one line doesn't seem to be good idea. Is there anything else I can do to format my code?
The parser will ignore white space characters in the source code. you can may <pre> or <br/> or fake it with CSS. but the solution you proposed is also valid and works, but as you stated it is ugly. if you are going for that you can use &Tab; char and it will create a tab indent; it makes more sense to use it instead of 4 x but you still need to put it inside <pre> tag to avoid being ignored by the parser.

markdown2 not adding <pre> to code snippets

Usually code snippets wrap the code tag with a pre tag. Looks like markdown is just using a p tag, is this normal?
from markdown2 import Markdown
markdowner = Markdown()
markdowner.convert("```\nthis is code\n```")
u'<p><code>\nthis is code\n</code></p>\n'
Even this website's adding pre tags. How do I add it to markdown?
is this normal?
Yes, fenced code blocks are not standard Markdown (only indented code blocks are). However, inline code spans can be deliminated with any number of backticks (as long as both opening an closing deliminators match). Therefore, the parser is correctly parsing your input as an inline code span which consists of a code tag inside a p tag. Of course, if you had inserted any blank lines, then the output would have been multiple paragraphs without any code spans (as the opening and closing deliminators would have been in separate paragraphs).
How do I add it to markdown?
As fenced code blocks are non-standard Markdown, they generally need to be enabled in parsers which support them. Each parser is different, so users should consult the documentation for their parser of choice. The other answer already covers how to enable them in the specific parser used by the OP.
Turns out markdown2 only adds pre's to what is indented by four spaces.
To add to above example, use:
markdown2.markdown(text, extras=["fenced-code-blocks"])
Reference

Process whitespaces from user input

The only reason why I include Python in the question is that PHP has the nl2br function that inserts br tags, a similar function in Python could be useful, but I suspect that this problem can be solved with HTML and CSS.
So, I have a form that receives user`s input in a textarea. I save it to the database, which is Postgres and then when I display it, it doesn't include the line breaks the user supplied to separate paragraphs.
I tried using the white-space CSS property on the paragraph tag:
white-space: pre
or
white-space: pre-wrap
But, this is weird, the result was separated lines but the first line aligned in the middle:
including text-align:left didn't solve the problem. I'm sure there is a simple solution to this.
I would suggest to replace newline characters with <br /> either before storing it in the database (only once) or when fetching it (see comment).
With Python:
import re
myUserInput = re.sub('(?:\r\n|\r|\n)', '<br />', myUserInput)
With JavaScript (see jsfiddle):
myUserInput = myUserInput.replace(/(?:\r\n|\r|\n)/g, '<br />');

Python Markdown nl2br extension

I'm a beginner programmer, and i've been trying to use the python markdown library in my web app. everything works fine, except the nl2br extension.
When I tried to convert text file to html using md.convert(text), it doesn't see to convert newlines to <br>.
for example, before I convert, the text is:
Puerto Rico
===========
------------------------------
### Game Rules
hello world!
after I convert, I get:
<h1>Puerto Rico</h1>
<hr />
<h3>Game Rules</h3>
<p>hello world!</p>
My understanding is that the blank spaces are represented by '\n' and should be converted to <br>, but I'm not getting that result. Here's my code:
import markdown
md = markdown.Markdown(safe_mode='escape',extensions=['nl2br'])
html = md.convert(text)
Please let me know if you have any idea or can point me in the right direction. Thank you.
Try adding two or more white spaces at the end of a line to insert <br/> tags
Example:
hello
world
results in
<p>hello <br>
world</p>
Notice that there are two spaces after the word hello. This only works if you have some text before the two spaces at the end of a line. But this has nothing to do with your nl2br extension, this is markdown standard.
My advice is, if you don't explicitly have to do this conversion, just don't do it. Using paragraphs alias <p>-tags is the cleaner way to seperate text regions.
If you simply want to have more space after your <h3> headlines then define some css for it:
h3 { margin-bottom: 4em; }
Image if you do spacing with <br>-tags after your headlines in all your 500 wiki pages and later you decide that it's 20px too much space. Then you have to edit all your pages by hand and remove two <br>-tags on every page. Otherwise you just edit one line in a css file.
Found this question looking for a clarification myself. Hence adding an update despite being 7 years late.
Reference thread on the Python Markdown Project: https://github.com/Python-Markdown/markdown/issues/707
Turns out that this is indeed the expected behaviour, and hence, the nl2br extension converts only single newlines occurring within a block, not around it. Which means,
This is
a block
This is a different
block
gets converted to
<p>This is<br/>block</p>\n<p>This is a different<br/>block</p>
but when you have distinct, separate blocks,
Puerto Rico
===========
------------------------------
### Game Rules
hello world!
all surrounding newlines are collapsed, and no <br/> tags are injected.
<h1>Puerto Rico</h1>
<hr />
<h3>Game Rules</h3>
<p>hello world!</p>

Categories

Resources