Python coding: I'm not sure about Nantoka so I looked it up

That makurakotoba written on the second line

For the time being, write shebang on the first line and write it on the second line.

haiku_wo_yome.py


#!/usr/bin/python
# -*- Coding: utf-8 -*-

It's a magical statement that defines how Python source code should be encoded. By the way, this example doesn't work. Because C is a capital letter. became addicted.

what's with that. What the heck coding: What is Nantoka? Let's check it out.

Read PEP 263

I tried to find out, but everything is written in PEP 263. As expected Python. That's why I'll try it.

Why is it necessary in the first place

Roughly speaking, Until Python 2.1, the only way to write Unicode characters was to use escape sequences. You can use any encoding you like for 8-bit characters, but there are limits. It seems that ... It's actually inconvenient. This area may be helpful for talking about character codes in Python. UTF-8 convenient.

How it works

Default is ASCII

If nothing is specified about the encoding, it will be interpreted as ASCII.

Write on the first or second line

Is it because there is a shebang that the second line is okay?

format

You can simply do this.

simple.py


# coding=<encoding name>

Often used:

emacs.py


#!/opt/local/bin/python
# -*- coding: <encoding name> -*-

This notation seems to be derived from Emacs. With vim:

vim.py


#!/emacs/or/vim/python
# vim: set fileencoding=<encoding name> :

How do you write it to be recognized?

Actually, when the first or second line matches the next pattern, the inside of the parentheses is recognized as the character code. [^ 1]

"coding[:=]\s*([-\w.]+)"

So, as long as you write it in a way that matches this, it will be consistent with the editor. In addition, the following notation is possible.

wazamae.py


#!/mongoose/vs/python
# This Python file uses the following encoding: utf-8

jillypoor.py


#!/neko/nadetai/python
# Current encoding: shift-jis is not good for this environment.

Recommended Posts

Python coding: I'm not sure about Nantoka so I looked it up
I thought "What is Linux?", So I looked it up.
I studied about Linux, so I summarized it.
AWS Lambda now supports Python so I tried it
I couldn't import the python module with VSCODE, but I could do it on juoyterlab, so I'm talking about finding the cause.
[Super basics of Python] I learned the basics of the basics, so I summarized it briefly.
I made a segment tree with python, so I will introduce it